算法面试之二叉树打印

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/a940902940902/article/details/79305282

关于二叉树打印解题关键如下:
使用Queue保存节点,当Queue不为空时进行循环判断。

Queue<TreeNode> queue=new LinkedList<TreeNode>();
queue.add(root);
while(!queue.isEmpty()){
.......
}

一种做法是设定两个指针,last和nlast,last标示当前打印的最右节点,nlast标示下一行的最右节点。初始时last指针和nlast指针都指向root节点,判断当前节点是否有左子节点以及右子节点,如果有将nlast指针指向其子节点,当当前指针指向的节点是last节点时,说明到了一行的末尾,此时输出换行,并将nlast节点值赋值给last节点(因为此时的nlast节点指向的是last节点下一层的最右节点)。

TreeNode last=root;
TreeNode nlast=root;
Queue<TreeNode> queue=new LinkedList<TreeNode>();
queue.add(root);
while(!queue.isEmpty()){
     TreeNode tmp=queue.poll();
     if(tmp.left!=null){
         queue.add(tmp.left);
         nlast=tmp.left;
     }
     if(tmp.right!=null){
         queue.add(tmp.right);
         nlast=tmp.right;
     }
     if(tmp==last){//当前到达last节点 则说明到达一行的末尾 需要输出换行
      System.out.println()// 输出换行
      last=nlast;//此时nlast一定指向的是下一层的末尾元素
}
}

第二种做法是通过判断queue中有多少个元素来对每层进行处理,首先判断queue中有多少元素,然后进行循环,对这些元素判断各自是否具有左右子节点,如果有则add进queue中,这样循环结束之后正好queue中就是下一行的全部元素。

 public List<List<Integer>> levelOrderBottom(TreeNode root) {
        List<List<Integer>> nodes=new ArrayList<List<Integer>>();
       if(root==null){
           return nodes;
       }
       Queue <TreeNode > node=new LinkedList<TreeNode>();
       node.add(root);
       while(!node.isEmpty()){
           List<Integer> path=new ArrayList<Integer>();
           int size=node.size();
           for(int i=0;i<size;i++){
               TreeNode tmp=node.poll();
               path.add(tmp.val);
               if(tmp.left!=null){
                   node.add(tmp.left);
               }
               if(tmp.right!=null){
                   node.add(tmp.right);
               }
           }
           nodes.add(path);
       }

关于二叉树打印主要有如下的考察:

  • 给定二叉树按照宽度优先遍历(层序遍历)输出每一行的内容,并输出行号
  • 给定二叉树,Z型层序输出,例如第一行正向输出,第二行反向输出
  • 二叉树的序列化和反序列化

猜你喜欢

转载自blog.csdn.net/a940902940902/article/details/79305282
今日推荐