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

从上往下打印二叉树

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

import java.util.ArrayList;
import java.util.LinkedList;
/**
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> ans = new ArrayList<Integer>();
        if(root == null) {
            return ans;
        }
        LinkedList<TreeNode> queue = new LinkedList<>();
        queue.addLast(root);
        while(!queue.isEmpty()) {
            int sz = queue.size();
            for(int i = 0; i < sz; i++) {
                TreeNode tmp = queue.removeFirst();
                ans.add(tmp.val);
                if(tmp.left  != null) queue.addLast(tmp.left);
                if(tmp.right != null) queue.addLast(tmp.right);
            }
        }
        return ans;
    }
}
全部评论

相关推荐

不愿透露姓名的神秘牛友
今天 14:23
点赞 评论 收藏
分享
但听说转正率很低,我现在有在实习了,好纠结要不要去
熬夜脱发码农:转正率低归低,但是实习的经历你可以拿着,又不是说秋招不准备了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务