小算法:二叉树的层次遍历(自底向上)

2019-03-27  本文已影响0人  cooooper

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

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

    3
   / \
  9  20
    /  \
   15   7

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

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

解答:

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

class Solution:
    def levelOrderBottom(self, root: TreeNode) -> List[List[int]]:
        if root == None:
            return []
        stack = [root]
        res = []
        while len(stack) != 0:
            tmp = []
            res_each = []
            for i in stack:
                res_each.append(i.val)
                if i.left != None:
                    tmp.append(i.left)
                if i.right != None:
                    tmp.append(i.right)
            stack = tmp
            res.insert(0,res_each)
        return res
上一篇下一篇

猜你喜欢

热点阅读