把二叉树打印成多行

把二叉树打印成多行

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

思路:做这题前先看看从上往下打印二叉树

import java.util.*;
public class Solution {
    public ArrayList<Integer> PrintFromTopToBottom(TreeNode root) {
         ArrayList<Integer> list = new ArrayList<Integer>();
        if(root==null)return list;

         Queue<TreeNode> queue = new LinkedList<TreeNode>();
        queue.offer(root);
        while(!queue.isEmpty()){
            TreeNode temp = queue.poll();
            list.add(temp.val);//给list复制还是要用.val
            if(temp.left!=null)queue.offer(temp.left);
            if(temp.right!=null)queue.offer(temp.right);
        }
        return list;
    }
}

然后发现这题就是在从上往下打印基础上多了个层次问题。在while中加个int size = queue.size();就vans了

import java.util.*;
public class Solution {
    ArrayList<ArrayList<Integer>> Print(TreeNode pRoot) {
        ArrayList<ArrayList<Integer>> thelist = new ArrayList<ArrayList<Integer>>();
        if(pRoot==null)return thelist; //这里要求返回thelist而不是null
        Queue<TreeNode> queue = new LinkedList<TreeNode>();
        queue.offer(pRoot);
        while(!queue.isEmpty()){
            ArrayList<Integer> list = new ArrayList<Integer>();
            int size = queue.size();
            for(int i=0;i<size;i++){
            TreeNode temp = queue.poll();
            list.add(temp.val);
            if(temp.left!=null)queue.offer(temp.left);
            if(temp.right!=null)queue.offer(temp.right);
            }
            thelist.add(list);
        }
        return thelist;
    }

}
全部评论
请问这里的list和thelist有什么区别啊
点赞 回复 分享
发布于 2020-07-31 10:27

相关推荐

不愿透露姓名的神秘牛友
07-09 12:05
点赞 评论 收藏
分享
06-17 21:57
门头沟学院 Java
白友:噗嗤,我发现有些人事就爱发这些,明明已读不回就行了,就是要恶心人
点赞 评论 收藏
分享
评论
35
1
分享

创作者周榜

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