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

从上往下打印二叉树

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

import java.util.*;
import java.util.ArrayList;
/**
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> rest = new ArrayList<>();
        Queue<TreeNode> que  = new ArrayDeque<TreeNode>();
        if(root == null){
            return rest;
        }
        //传入的链表存储
        que.offer(root);
        while(!que.isEmpty()){
            TreeNode cur = que.poll();
            rest.add(cur.val);
            //若是左右孩子存在,则存入左右孩子作为下一个层次
            if(cur.left != null){
                que.add(cur.left);
            }
             if(cur.right != null){
                que.add(cur.right);
            }
        }
        return rest;
    }
}

全部评论

相关推荐

牛至超人:把哈工大,再加大加粗,看见闪闪发光的哈工大字样,面试官直接流口水
投递字节跳动等公司6个岗位
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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