LeetCode 107.Binary Tree Level Order Traversal II

Posted zeroingToOne

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode 107.Binary Tree Level Order Traversal II相关的知识,希望对你有一定的参考价值。

Given a binary tree, return the bottom-up level order traversal of its nodes‘ values. (ie, from left to right, level by level from leaf to root).

For example:
Given binary tree [3,9,20,null,null,15,7],

    3
   /   9  20
    /     15   7

 

return its bottom-up level order traversal as:

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

题意:给定一个二叉树,从叶子结点开始,从左往右,从上往下地返回二叉树中的所有结点。
思路:层次遍历,
建立一个queue,先将根节点放进去,用while循环判断queue是否为空,不为空时,建立一个存放结点数值的链表,获取当前queue的结点个数,建立for循环,将当前结点的值val放入新链表中,再判断当前结点的左右子树是否为空,不为空则将子树存入queue。for循环结束后,将存放结点数值的链表存入list的首位。
代码如下:
public List<List<Integer>> levelOrderBottom(TreeNode root) {
        List<List<Integer>> list = new LinkedList<List<Integer>>();
        if (root == null)
            return list;
        Queue<TreeNode> subList = new LinkedList<>();
        int size = 0;
        subList.add(root);
        while (!subList.isEmpty()) {
            List<Integer> subListInt = new LinkedList<>();
            size = subList.size();// 判断当前层中结点个数
            for (int i = 0; i < size; i++) {
                TreeNode t = subList.poll();//获取并移除此队列的头元素
                subListInt.add(t.val);// 存入当前结点的值val

                if (t.left != null)// 将下一层的结点存入链表中
                    subList.add(t.left);
                if (t.right != null)
                    subList.add(t.right);
            }
            ((LinkedList<List<Integer>>) list).addFirst(subListInt);
        }
        return list;
    }

 

 






以上是关于LeetCode 107.Binary Tree Level Order Traversal II的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode107. Binary Tree Level Order Traversal II 解题报告

LeetCode_107. Binary Tree Level Order Traversal II

Leetcode 107 Binary Tree Level Order Traversal II

LeetCode107 Binary Tree Level Order Traversal II

Leetcode 107. Binary Tree Level Order Traversal II

LeetCode 107.Binary Tree Level Order Traversal II