题解 | #从上往下打印二叉树#

从上往下打印二叉树

http://www.nowcoder.com/practice/7fe2212963db4790b57431d9ed259701

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;


/**
public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;

    public TreeNode(int val) {
        this.val = val;

    }

}
*/
public class Solution {
    public ArrayList<Integer> PrintFromTopToBottom(TreeNode root) {
        //层序遍历
        ArrayList<Integer> arr = new ArrayList<Integer> ();
        Queue<TreeNode>q = new LinkedList<TreeNode>();
        if(root!=null) q.offer(root);
        while(!q.isEmpty()){
            TreeNode t = q.poll();
            arr.add(t.val);
            if(t.left!=null) q.offer(t.left);
            if(t.right!=null) q.offer(t.right);
        }
        return arr;
    }
}

标准的利用队列实现层序遍历

全部评论

相关推荐

评论
点赞
收藏
分享
牛客网
牛客企业服务