题解 | #把二叉树打印成多行#

把二叉树打印成多行

http://www.nowcoder.com/practice/445c44d982d04483b04a54f298796288

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 {
    ArrayList<ArrayList<Integer> > Print(TreeNode root) {
        ArrayList<ArrayList<Integer>> ans = new ArrayList<>();
        if(root == null) {
            return ans;
        }
        LinkedList<TreeNode> queue = new LinkedList<>();
        queue.addLast(root);
        while(!queue.isEmpty()) {
            int sz = queue.size();
            ArrayList<Integer> lvl = new ArrayList<>();
            for(int i = 0; i < sz; i++) {
                TreeNode tmp = queue.removeFirst();
                lvl.add(tmp.val);
                if(tmp.left != null)  queue.addLast(tmp.left);
                if(tmp.right != null) queue.addLast(tmp.right);
            }
            ans.add(lvl);
        }
        return ans;
    }
    
}



全部评论

相关推荐

嵐jlu:我是山川🐔里🐔🧱的,阿里系简历全过; 你这简历一看就还是半成品啊,没有荣誉经历奖项什么的吗?
投递阿里巴巴集团等公司9个岗位
点赞 评论 收藏
分享
牛客刘北:如果暑期实习是27届的话,你要晚一年才会毕业,企业为什么会等你呢?要搞清时间逻辑呀!27届现在实习只能是在暑假实习,这是日常实习,不是暑期实习。所以多去投日常实习吧,暑期实习肯定不会要你的
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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