递归真的不怎么会写。。
Java,这里使用了递归,借助另一个函数计算层级
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public List<List<Integer>> levelOrderBottom(TreeNode root) {
List<List<Integer>> result=new LinkedList<List<Integer>>();
count(result,root,0);
return result;
}
public void count(List<List<Integer>> list,TreeNode root,int level)
{
if(root==null) return;
if(level>=list.size())
{
list.add(0,new LinkedList<Integer>());
}
count(list,root.left,level+1);
count(list,root.right,level+1);
list.get(list.size()-level-1).add(root.val);
}
}
Java,基于这题是求每行的节点值组成数组,用广搜更合适
public class Solution {
public List<List<Integer>> levelOrderBottom(TreeNode root) {
List<TreeNode> toUse = new ArrayList<>();
List<List<Integer>> retValue = new ArrayList<>();
if( root != null)
{
toUse.add(root);
}
while (toUse.size() != 0)
{
List<Integer> result = new ArrayList<>();
List<TreeNode> next = new ArrayList<>();
for (TreeNode node : toUse)
{
result.add(node.val);
if (node.left != null)
{
next.add(node.left);
}
if (node.right != null)
{
next.add(node.right);
}
}
retValue.add(result);
toUse = next;
}
Collections.reverse(retValue);
return retValue;
}