牛客网剑指offer编程题——从上往下打印二叉树(Java)

解题思路:从上往下打印,则是父节点—>左子节点—>右子节点的顺序,总的来说顺序是很明确的,左子节点的子节点也优先于右子节点的子节点,所以只要从左往右依次遍历左右子节点,子节点的子节点也能是顺序排列的,队列可以满足该需求


代码如下:

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;/**
public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;

    public TreeNode(int val) {
        this.val = val;

    }

}
*/
public class Solution {
    public ArrayList PrintFromTopToBottom(TreeNode root) {
        
        ArrayList list = new ArrayList();

        LinkedList queue = new LinkedList();
		if(root == null){
            return new ArrayList();
        }
        TreeNode temp = root;
        queue.add(temp);
        while (!queue.isEmpty()){
            temp = (TreeNode)queue.poll();
            list.add(temp.val);
            if(temp.left != null){
                queue.add(temp.left);
            }
            if(temp.right != null){
                queue.add(temp.right);
            }

        }
       return list;
    }
}

end

你可能感兴趣的:(Java,算法)