从上往下打印二叉树

思路:
每次打印一个节点时,如果这个节点有子节点,就把该节点的子节点,放入到一个队列的尾部。接下来,把最早进入队列的头部节点取出来,重复打印操作。

Paste_Image.png

Paste_Image.png
public class Solution {
    public ArrayList<Integer> PrintFromTopToBottom(TreeNode root) {
       Queue<TreeNode> queue=new LinkedList<TreeNode>();
       ArrayList<Integer>  res=new ArrayList<Integer>();
       if(root==null)
          return res;
       queue.offer(root);
       TreeNode temp=null;
       while(!queue.isEmpty()){
           temp=queue.poll();
           res.add(temp.val);
           if(temp.left!=null)
                queue.add(temp.left);
           if(temp.right!=null)
                queue.add(temp.right);
       }
       return res;
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容