剑指offer-60-二叉树打印成行

把二叉树打印成多行

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

思路

用Queue保存一行结点,每次遍历一整行

代码

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;

public class Solution {
    ArrayList<ArrayList<Integer>> Print(TreeNode pRoot){
        ArrayList<ArrayList<Integer>> result = new ArrayList<>();
        if(pRoot==null){
            return result;
        }
        Queue<TreeNode> q = new LinkedList<>();
        q.add(pRoot);
        while (!q.isEmpty()) {
            ArrayList<Integer> temp = new ArrayList<>();
            Queue<TreeNode> tempQ = new LinkedList<>();
            while (!q.isEmpty()) {
                TreeNode t = q.poll();
                temp.add(t.val);
                if(t.left != null){
                    tempQ.offer(t.left);
                }
                if(t.right != null){
                    tempQ.offer(t.right);
                }
            }
            result.add(temp);
            q = tempQ;
        }
        return result;
    }
}
剑指offer与数据结构 文章被收录于专栏

本专栏包括剑指offer题目和一些刷题用的数据结构,单调栈,树状数组,差分数组,后面还会更新红黑树等较为复杂的数据结构

全部评论

相关推荐

点赞 评论 收藏
分享
04-11 21:31
四川大学 Java
野猪不是猪🐗:(ja)va学弟这招太狠了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务