Leetcode __107. 二叉树的层次遍历

问题描述

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

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

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

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

思路

从左到右:用到了 队列的先进先出;
从低到上:用到了链表增加元素特性,每次在表头插入一个元素,其他元素依次顺延;

实现

   public List<List<Integer>> levelOrderBottom(TreeNode root) {
        List<List<Integer>> list = new LinkedList<List<Integer>>();
        if (root == null)
            return list;
        List<Integer> intList = new LinkedList<Integer>();
        Queue<TreeNode> queue = new LinkedList<TreeNode>();
        TreeNode t = null;
        queue.offer(root);
        int curCount = 0, curNum = 1, nextCount = 1;
        while (!queue.isEmpty()) {
            t = queue.poll();//删除并返回队头元素,第一次为根元素,下次从每层的左边第一个元素开始
            intList.add(t.val);//存入链表
            if (t.left != null) {
                queue.offer(t.left);//添加一个元素并返回true
                nextCount++;
            }
            if (t.right != null) {
                queue.offer(t.right);
                nextCount++;
            }
            if (++curCount == curNum) {
                list.add(0, intList);//增加元素,每次在0位置插入元素,其他往后顺延
                intList = new LinkedList<Integer>();
                curNum = nextCount;
            }
        }
        return list;
    }

从根节点开始,入队列,进入循环后,取出元素存入链表并出队列,再把根的下一层节点从左到右入队列,//curNum当前行最后一个元素的序号//nextCount下一行的最后一个元素的序号//curCount当前元素的序号

猜你喜欢

转载自blog.csdn.net/Growing_way/article/details/82689936