题目:要求按深度从下到上访问二叉树,每层顺序从左到右。
例如:
Given binary tree{3,9,20,#,#,15,7},
3
/ \
9 20
/ \
15 7
return its bottom-up level order traversal as:
[
[15,7]
[9,20],
[3],
]
方法:
仍是从上向下层序遍历二叉树,用ArrayList保存每层结点信息,以null作为每层的分隔符,当遍历完二叉树后,反向遍历ArrayList。
代码如下:
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
import java.util.*;
public class Solution {
public ArrayList<ArrayList<Integer>> levelOrderBottom(TreeNode root) {
ArrayList<ArrayList<Integer>> matrix=new ArrayList();
if(root == null)
return matrix;
ArrayList<TreeNode> list=new ArrayList();
saveLevelOrder(root,list);//层序遍历保存在list中;
ArrayList<Integer> array=new ArrayList();
for(int index=list.size()-2;index>=0;index--)//跳过最后一个null;
{
if(list.get(index) == null)
{
matrix.add(array);
array=new ArrayList();
}else
{
array.add(0,list.get(index).val);
}
}
matrix.add(array);//最后的一个保存有root结点信息的array没有在while循环中保存,所以单独保存;
return matrix;
}
public void saveLevelOrder(TreeNode root,ArrayList<TreeNode> list)
{
list.add(root);
list.add(null);//第0层末尾的null;
int cur=0;//cur表示当前结点在list中的index;
while(cur<list.size())
{
int next=list.size();//next表示下一层末尾结点的位置的后一个位置;
while(cur<next)
{
TreeNode node=list.get(cur);//放在while循环外面导致cur不变化而出错;
if(node!=null)//避免 NullPointerException;
{
if(node.left!=null)
{
list.add(node.left);
}
if(node.right!=null)
{
list.add(node.right);
}
}
cur++;
}
if(cur == list.size())//不加这个判断会出现死循环情况,不断在list末尾加null;
{
break;
}
list.add(null);//用null作为每层的分隔符;
}
}
}