剑指Offer二十二:从上到下打印二叉树

题干

从上往下打印出二叉树的每个节点,同层节点从左至右打印。

思路

从上到下打印二叉树就是层序遍历,这里可以借鉴我之前写过的博文二叉树的遍历

代码

public class Solution {
    public ArrayList<Integer> PrintFromTopToBottom(TreeNode root) {
 Queue<TreeNode> queue=new LinkedList<TreeNode>();
        ArrayList<Integer> array=new ArrayList<Integer>();
        if(root==null)return array;
        queue.offer(root);
       // array.add(root.val); 如何进行表示表示他们是在同一层 是个问题的关键所在  可以利用for循环来实现判断是否还存在数据供我们访问,是一个经典所在。
        while(queue.size()!=0){
            int len=queue.size();          
            for(int i=0;i<len;i++){
                 TreeNode temp=queue.poll();
            if(temp.left!=null){
                queue.add(temp.left);
            }
            if(temp.right!=null){
                queue.add(temp.right);
            }
                array.add(temp.val);
            }
        }
        return array;

    }
}
发布了42 篇原创文章 · 获赞 16 · 访问量 1642

猜你喜欢

转载自blog.csdn.net/weixin_44015043/article/details/105352736