Binary Tree Level Order Traversal II 解答

时间:2022-10-04 15:43:02

Question

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]
]

Solution

Same method as "Binary Tree Level Order Traversal". Note that for ArrayList, it has function add(int index, E element).

 /**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public List<List<Integer>> levelOrderBottom(TreeNode root) {
List<List<Integer>> result = new ArrayList<List<Integer>>();
if (root == null)
return result;
Deque<TreeNode> prev = new ArrayDeque<TreeNode>();
Deque<TreeNode> current;
TreeNode tmpNode;
prev.addLast(root);
while (prev.size() > 0) {
current = new ArrayDeque<TreeNode>();
List<Integer> tmpList = new ArrayList<Integer>();
while (prev.size() > 0) {
tmpNode = prev.pop();
if (tmpNode.left != null)
current.addLast(tmpNode.left);
if (tmpNode.right != null)
current.addLast(tmpNode.right);
tmpList.add(tmpNode.val);
}
prev = current;
result.add(0, tmpList);
}
return result;
}
}