For example:
Given binary tree
{3,9,20,#,#,15,7}
,3 / \ 9 20 / \ 15 7return its level order traversal as:
[ [3], [9,20], [15,7] ]
Confused what
"{1,#,2,3}"
means? > read more on how binary tree is serialized on OJ.---
Solution: Maintain a list of list as the answer. Traverse in pre-order with the depth information. For each node of depth D, add it to the list with index D, where D=0 for the root node.
It does not matter if you traverse pre-order, in-order, or post-order. The result will be the same for any traversal order.
/**
* 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>> levelOrder(TreeNode root) {
List<List<Integer>> answer = new ArrayList<>();
traverse(answer, root, 0);
return answer;
}
private void traverse(List<List<Integer>> answer, TreeNode node, int depth) {
if (node == null) return;
while (answer.size() <= depth) answer.add(new ArrayList<Integer>());
answer.get(depth).add(node.val);
traverse(answer, node.left, depth + 1);
traverse(answer, node.right, depth + 1);
}
}
No comments:
Post a Comment