题解 | #求二叉树的层序遍历#
求二叉树的层序遍历
http://www.nowcoder.com/practice/04a5560e43e24e9db4595865dc9c63a3
通过先序遍历获取每一层级的元素,保存到每一层对应的容器里。
//import java.util.List;
import java.util.ArrayList;
/*
* public class TreeNode {
* int val = 0;
* TreeNode left = null;
* TreeNode right = null;
* }
*/
public class Solution {
/**
*
* @param root TreeNode类
* @return int整型ArrayList<ArrayList<>>
*/
public ArrayList<ArrayList<Integer>> levelOrder (TreeNode root) {
// write code here
ArrayList<ArrayList<Integer>> res = new ArrayList<>();
pre(root,0,res);
return res;
}
public void pre(TreeNode root,int n, ArrayList<ArrayList<Integer>> res){
if(null == root)
return;
if(n >= res.size())
res.add(new ArrayList<>());
res.get(n).add(root.val);
pre(root.left,n+1,res);
pre(root.right,n+1,res);
}
}