题目描述:

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

  解题思路:

  本题实际上就是二叉树的层次遍历,深度遍历可以用递归或者栈,而层次遍历很明显应该使用队列。同样我们可以通过一个例子来分析得到规律:每次打印一个结点时,如果该结点有子结点,则将子结点放到队列的末尾,接下来取出队列的头重复前面的打印动作,直到队列中所有的结点都打印完毕。

  举例:

【剑指Offer】22、从上往下打印二叉树
【剑指Offer】22、从上往下打印二叉树

  编程实现(Java):

    public ArrayList<Integer> PrintFromTopToBottom(TreeNode root) {
        //思路:使用队列来实现
        ArrayList<Integer> res=new ArrayList<>();
        if(root==null)
            return res;
        Queue<TreeNode> queue=new LinkedList<>(); //定义一个队列
        queue.add(root);
        while(queue.size()!=0){
            TreeNode 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;
    }

相关文章:

  • 2021-09-19
  • 2022-01-23
  • 2021-09-23
  • 2022-02-09
  • 2021-10-17
  • 2022-12-23
  • 2021-10-18
猜你喜欢
  • 2022-02-27
  • 2022-01-19
  • 2021-07-20
  • 2022-01-14
  • 2021-07-05
  • 2021-09-21
  • 2022-01-07
相关资源
相似解决方案