思路很简单,不难想。 就是从根节点开始,将每一层的节点存在list中。之后遍历list中的每个节点,将每个节点的非空子节点再存在该list中得到下一层节点.....直到list为空,即得到了每一层的节点。 题目要求按照从底到根的顺序,那么要求下一层要插在上一层的前面。 这里利用了我没用过的忽视掉的ArrayList.add(int pos,object o)这个方法。通常使用add方法往往是将o加入list的尾部。但是加入一个参数可以指定插入的位置。 这样,我们令每一层都插入到list的第一个,这样,list最终的顺序就是从底到根。
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public ArrayList<ArrayList<Integer>> levelOrderBottom(TreeNode root) {
ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();
ArrayList<TreeNode> current = new ArrayList<TreeNode>();
if( root==null )
{
return res;
}
current.add(root);
while(!current.isEmpty())
{
ArrayList<Integer> tmp = new ArrayList<Integer>();
ArrayList<TreeNode> next = new ArrayList<TreeNode>();
for( TreeNode t:current )
{
tmp.add(t.val);
if(t.left!=null)
{
next.add(t.left);
}
if(t.right!=null)
{
next.add(t.right);
}
}
res.add(0,tmp);
current = next;
}
return res;
}
}