Binary Tree Level Order Traversal
Given a binary tree, return the level order traversal of its nodes’ values. (ie, from left to right, level by level).
For example:
Given binary tree {3,9,20,#,#,15,7},
[[3], [9,20], [15,7]]
tiyi:每层节点是一个子数组
代码:
public class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> res = new ArrayList<List<Integer>>();
traversal(res, root, 0);
return res;
}
public void traversal(List<List<Integer>> res, TreeNode root, int height){
if(root == null) return;
if(height >= res.size()){
res.add(new LinkedList<Integer>());
}
res.get(height).add(root.val);
traversal(res, root.left, height+1);
traversal(res, root.right, height+1);
}
}