树——从最下层向上打印二叉树(层序遍历扩展)

题目:要求按深度从下到上访问二叉树,每层顺序从左到右。

例如:

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作为每层的分隔符;   
        }
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值