其他分享
首页 > 其他分享> > 从上到下打印二叉树

从上到下打印二叉树

作者:互联网

解题:利用队列先进先出来实现层次遍历

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {//层次遍历
    Queue<TreeNode> q = new LinkedList<>();
    List<Integer> list = new ArrayList<Integer>();
    public int[] levelOrder(TreeNode root) {
    if(root == null) return new int[0];    
    q.add(root);
    list.add(root.val);
        while(true){
            for(int i=0;i<q.size();i++){//q.size()控制当前层元素个数,要出多少次队列
                TreeNode t = q.poll();
                if(t.left != null){
               q.add(t.left);
               list.add(t.left.val);
                }
                if(t.right != null){
                q.add(t.right);
                list.add(t.right.val);
                }
            }
            if(q.size() == 0) break;
        }
        int n = list.size();
        int []res = new int [n];
        for(int i=0;i<n;i++)
        res[i] = list.get(i);
        return res;    
    }
}

标签:TreeNode,val,int,打印,list,二叉树,new,root,从上到下
来源: https://www.cnblogs.com/cstdio1/p/13336353.html