zoukankan      html  css  js  c++  java
  • 从上往下打印二叉树

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

    思路:就是写一个层序遍历代码,用队列将根、左孩子、右孩子有序入队最后再出队即可

     1 import java.util.*;
     2 /**
     3 public class TreeNode {
     4     int val = 0;
     5     TreeNode left = null;
     6     TreeNode right = null;
     7 
     8     public TreeNode(int val) {
     9         this.val = val;
    10 
    11     }
    12 
    13 }
    14 */
    15 public class Solution {
    16     
    17     Queue<TreeNode> queue = new LinkedList<>();
    18     ArrayList<Integer> arr = new ArrayList();
    19     
    20     public ArrayList<Integer> PrintFromTopToBottom(TreeNode root) {
    21         
    22         if(root==null)
    23             return arr;
    24         queue.add(root);
    25         while(!queue.isEmpty()){
    26             TreeNode t = queue.poll();//好久没用过队列函数不太清楚了!!!
    27             arr.add(t.val);
    28             if(t.left!=null)
    29                 queue.add(t.left);
    30             if(t.right!=null)
    31                 queue.add(t.right);
    32         }
    33         return arr;
    34     }
    35 }

    代码一天不敲就生疏(ps:每天都敲也菜。。。。。)

  • 相关阅读:
    计数排序【代码】
    快速排序【代码】
    基于最大堆实现最大优先队列
    Spring入门(1)
    AJAX初步理解
    选择器
    Hibernate的映射
    Hibernate配置(2)
    查看mysql的安装路径
    Hibernate入门(1)
  • 原文地址:https://www.cnblogs.com/haq123/p/12189786.html
Copyright © 2011-2022 走看看