LeetCode每日一题:二叉树层次遍历

问题描述

Given a binary tree, return the bottom-up level order traversal of its nodes' values. (ie, from left to right, level by level from leaf to root).
For example:
Given binary tree{3,9,20,¥,¥,15,7},
3
/
9 20
/
15 7

return its bottom-up level order traversal as:
[
[15,7]
[9,20],
[3],
]

confused what"{1,#,2,3}"means? > read more on how binary tree is serialized on OJ.

OJ's Binary Tree Serialization:
The serialization of a binary tree follows a level order traversal, where ‘¥’ signifies a path terminator where no node exists below.
Here's an example:
1
/
2 3
/
4

5
The above binary tree is serialized as”{1,2,3,¥,¥,4,¥,¥,5}”.

问题分析

这题考的是标准的二叉树层次遍历,用队列就可以解决了,要注意答案是要倒序输出,所以每次add到0的位置,把前面的层向后挤就行了

代码实现

public ArrayList> levelOrderBottom(TreeNode root) {
        ArrayList> result = new ArrayList<>();
        if (root == null) return result;
        Queue queue = new LinkedList<>();
        queue.offer(root);
        while (queue.isEmpty() == false) {
            ArrayList list = new ArrayList<>();
            int size = queue.size();
            for (int i = 0; i < size; i++) {
                TreeNode curNode = queue.poll();
                list.add(curNode.val);
                if (curNode.left != null) queue.offer(curNode.left);
                if (curNode.right != null) queue.offer(curNode.right);
            }
            result.add(0, list);
        }
        return result;
    }

你可能感兴趣的:(LeetCode每日一题:二叉树层次遍历)