leetcode 107. 二叉树的层次遍历 II(java)

给定一个二叉树,返回其节点值自底向上的层次遍历。 (即按从叶子节点所在层到根节点所在的层,逐层从左向右遍历)

例如:
给定二叉树 [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7

返回其自底向上的层次遍历为:

[
  [15,7],
  [9,20],
  [3]
]
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public List<List<Integer>> levelOrderBottom(TreeNode root) {
        List<List<Integer>> result=new ArrayList();
        List<TreeNode> list=new ArrayList();
        if(root==null) return result;
        list.add(root);
        while(!list.isEmpty()){       
            List<Integer> curList=new ArrayList();//每次当前层节点都要重新初始化
            List<TreeNode> nextList=new ArrayList();//初始化下一层所有节点的list
            for(TreeNode cur:list){//cur是当前节点,list是当前层的所有节点
                curList.add(cur.val);
                if(cur.left!=null) nextList.add(cur.left);//下一层节点
                if(cur.right!=null) nextList.add(cur.right);//下一层节点
            }
            list=nextList;
            result.add(0,curList);//当前层所有节点的list倒插进返回结果中
        }
        return result;
    }
}

为什么要创建这么多ArrayList呢?

首先,因为程序要求返回的是List<List<Integer>>,也就是说需要创建一个List<List<Integer>>的ArrayList用于返回,还需要一个List<Integer>向List<List<Integer>>中添加数组,例 [[1],[2,3],[4,5,6]]。

然而只有Integer显然不行,寻找当前节点的左孩子和右孩子当然需要TreeNode类型,所以有了程序中的 list 和 nextList。list表示当前层的所有节点,nextList表示下一层的所有节点。

猜你喜欢

转载自blog.csdn.net/weixin_40449300/article/details/84309944