美文网首页
小算法:二叉树的层次遍历(自底向上)

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

作者: cooooper | 来源:发表于2019-03-27 10:31 被阅读0次

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

    示例 :
    给定二叉树 [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
    

    相关文章

      网友评论

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

          本文链接:https://www.haomeiwen.com/subject/yavavqtx.html