【leetcode】107二叉树的反向层序遍历

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

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

    3
   / \
  9  20
    /  \
   15   7
返回其自底向上的层次遍历为:

[
  [15,7],
  [9,20],
  [3]
]

层序遍历每一行,然后进行链表头插,注意点:进行空的控制输出的是链表的空,而不是null。

/**
 * 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>> list = new ArrayList<>();
        if(root == null)
            return list;
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while(!queue.isEmpty()){
            List<Integer> list1 = new LinkedList<>();
            int size = queue.size();
            while(size>0){
                TreeNode cur = queue.poll();
                list1.add(cur.val);
                if(cur.left != null)
                    queue.offer(cur.left);
                if(cur.right != null)
                    queue.offer(cur.right);
                size --;
            }
            list.add(0,list1);
        }
        return list;
    }
}
发布了139 篇原创文章 · 获赞 93 · 访问量 5万+

猜你喜欢

转载自blog.csdn.net/weixin_43271086/article/details/105550743