Skip to content

Latest commit

 

History

History
32 lines (27 loc) · 921 Bytes

32.2 把二叉树打印成多行.md

File metadata and controls

32 lines (27 loc) · 921 Bytes

32.2 把二叉树打印成多行

NowCoder

题目描述

和上题几乎一样。

解题思路

ArrayList<ArrayList<Integer>> Print(TreeNode pRoot) {
    ArrayList<ArrayList<Integer>> ret = new ArrayList<>();
    Queue<TreeNode> queue = new LinkedList<>();
    queue.add(pRoot);
    while (!queue.isEmpty()) {
        ArrayList<Integer> list = new ArrayList<>();
        int cnt = queue.size();
        while (cnt-- > 0) {
            TreeNode node = queue.poll();
            if (node == null)
                continue;
            list.add(node.val);
            queue.add(node.left);
            queue.add(node.right);
        }
        if (list.size() != 0)
            ret.add(list);
    }
    return ret;
}