算法学习

算法题--从底向上分层收集二叉树中的节点值

2020-04-29  本文已影响0人  岁月如歌2020
image.png

0. 链接

题目链接

1. 题目

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]
]

2. 思路1: 递归实现

level=1
results.insert(0, list())
results[len(results) - level].append(node.val)

3. 代码

# coding:utf8
from typing import List


# Definition for a binary tree node.
class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right


class Solution:
    def levelOrderBottom(self, root: TreeNode) -> List[List[int]]:

        def check(results, node, level=1):
            if len(results) < level:
                results.insert(0, list())
            results[len(results) - level].append(node.val)
            if node.left is not None:
                check(results, node.left, level + 1)
            if node.right is not None:
                check(results, node.right, level + 1)

        results = list()
        if root is not None:
            check(results, root)
        return results


solution = Solution()

root1 = node = TreeNode(3)
node.left = TreeNode(9)
node.right = TreeNode(20)
node.right.left = TreeNode(15)
node.right.right = TreeNode(7)

print(solution.levelOrderBottom(root1))


输出结果

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

4. 结果

image.png

5. 利用队列(BFS)

6. 代码

class Solution1:
    def levelOrderBottom(self, root: TreeNode) -> List[List[int]]:
        results = list()
        if root is None:
            return results

        queue = list()
        queue.append(root)

        while len(queue) > 0:
            level_num = len(queue)
            sub_list = list()
            for i in range(level_num):
                if queue[0].left is not None:
                    queue.append(queue[0].left)
                if queue[0].right is not None:
                    queue.append(queue[0].right)
                sub_list.append(queue.pop(0).val)
            results.insert(0, sub_list)

        return results


solution = Solution1()

root1 = node = TreeNode(3)
node.left = TreeNode(9)
node.right = TreeNode(20)
node.right.left = TreeNode(15)
node.right.right = TreeNode(7)

print(solution.levelOrderBottom(root1))

输出结果

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

7. 结果

image.png
上一篇 下一篇

猜你喜欢

热点阅读