给定一个二叉树,返回其节点值自底向上的层序遍历。 (即按从叶子节点所在层到根节点所在的层,逐层从左向右遍历)
例如:
给定二叉树 [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回其自底向上的层序遍历为:
[
[15,7],
[9,20],
[3]
]
解答
class Solution {
public List<List<Integer>> levelOrderBottom(TreeNode root) {
if (root == null) return new LinkedList<>();
Stack<List<Integer>> stack = new Stack<>();
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
TreeNode node;
int remainNodes = 0;
List<Integer> currLevel = new LinkedList<>();
// 遍历层
while (!queue.isEmpty()) {
if (remainNodes == 0) {
currLevel = new LinkedList<>();
remainNodes = queue.size();
}
// 层中遍历节点
while (remainNodes > 0) {
node = queue.poll();
remainNodes--;
currLevel.add(node.val);
if (node.left != null) queue.add(node.left);
if (node.right != null) queue.add(node.right);
}
stack.push(currLevel);
}
List<List<Integer>> result = new LinkedList<>();
while (!stack.isEmpty()) { result.add(stack.pop()); }
return result;
}
}