题目描述:
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,null,null,15,7]
,
3 / \ 9 20 / \ 15 7
return its level order traversal as:
[ [3], [9,20], [15,7] ]
中文理解:
给定给定一颗二叉树,返回该二叉树的层次遍历结果。
解题思路:
使用递归方法,递归过程中带有表示层的level变量,然后将level相同的放入相同序列,最后返回即可。
代码(java):
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> list=new ArrayList();
if(root==null)return list;
levelOrderHelper(list,root,0);
return list;
}
public void levelOrderHelper(List<List<Integer>> list,TreeNode root,int level){
if(root==null)return;
if(level>list.size()-1){
List<Integer> temp=new ArrayList();
temp.add(root.val);
list.add(new ArrayList(temp));
}
else{
List<Integer> temp=list.get(level);
temp.add(root.val);
//list.add(new ArrayList(temp));
}
levelOrderHelper(list,root.left,level+1);
levelOrderHelper(list,root.right,level+1);
}
}