For example:
Given binary tree
{3,9,20,#,#,15,7}
,3 / \ 9 20 / \ 15 7return 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.---
Solution: Add each level of nodes as a list. Collect all the children nodes first. Then collect the integer values as a list. Add this list to the front of the answer list.
/**
* 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) {
LinkedList<List<Integer>> answer = new LinkedList<>();
if (root == null) return answer;
List<TreeNode> nodes = new ArrayList<>();
List<TreeNode> children = new ArrayList<>();
nodes.add(root);
do {
List<Integer> list = new ArrayList<>();
for (TreeNode node: nodes) {
list.add(node.val);
if (node.left != null) children.add(node.left);
if (node.right != null) children.add(node.right);
}
answer.addFirst(list);
nodes.clear();
List<TreeNode> tmp = nodes;
nodes = children;
children = tmp;
} while (!nodes.isEmpty());
return answer;
}
}
No comments:
Post a Comment