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

从上往下打印二叉树

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;
    }
}
全部评论

相关推荐

牛客464620405号:随便投,随便找,中国经过40多年的改革开放,人才缺口和职位空缺是巨大的,中国现在属于遍地黄金的年代,属于90后和00大机遇的时代
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务