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

把二叉树打印成多行

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

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;
/*
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 pRoot) {
        ArrayList<ArrayList<Integer> > ans = new ArrayList<ArrayList<Integer> >();
        if(pRoot==null) return ans;
        Queue<TreeNode>q = new LinkedList<TreeNode>();
        TreeNode cut = new TreeNode(-1);
        q.offer(pRoot); 
        q.offer(cut);
        while(!q.isEmpty()){
            TreeNode t = q.poll();
            ArrayList<Integer> list = new ArrayList<Integer>();
            while(t!=cut){
                list.add(t.val);
                if(t.left!=null) q.offer(t.left);
                if(t.right!=null) q.offer(t.right);
                t = q.poll();
            }
            ans.add(list);
            if(!q.isEmpty())
                q.offer(cut);
        }
        return ans;
    }
    
}

思路:每一层结束后插入一个cut结点来分隔每一层

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务