Given a binary tree, return thelevel ordertraversal of its nodes' values. (ie, from left to right, level by level).
For example:
Given binary tree[3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
return its level order traversal as:
[
[3],
[9,20],
[15,7]
]
Note:
in Binary Tree Level Order Traversal II, the requirement is only different in getting the outcome as reverse order, namely bottom-up level order traversal as:
[
[15,7],
[9,20],
[3]
]
Analysis
Recursive - DFS
关键在传入一个结果的list,因为list中元素的序号代表了层数(n+1)
Queue
利用一个Queue记录需要扫描的层(level)的节点数(number of nodes),依次存入每个节点的左子节点和右子节点到Queue中,读取时依次从Queue取出节点并存入该层sub list,每层扫描完后存入总的wrap list。
Solution
Top-down level order traversal
Using Recursive - DFS
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */classSolution {publicList<List<Integer>> levelOrder(TreeNode root) {List<List<Integer>> result =newArrayList<List<Integer>>();levelOrderHelper(root,0, result);return result; }voidlevelOrderHelper(TreeNode root,int depth,List<List<Integer>> result) {if (root ==null) {return; }if (depth ==result.size()) {result.add(newArrayList<Integer>()); }result.get(depth).add(root.val);levelOrderHelper(root.left, depth +1, result);levelOrderHelper(root.right, depth +1, result); }}