leetCode#107. Binary Tree Level Order Traversal II

本文介绍了一种解决二叉树底部向上层次遍历的方法,通过三种不同的实现方式,逐步优化算法性能,最终提供了一个简洁高效的解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Description

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

以下代码中的stack变量应该命名为queue,以免误导

Code

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

class Solution(object):
    def levelOrderBottom(self, root):
        """
        :type root: TreeNode
        :rtype: List[List[int]]
        """
        return self.getList([root], [], 1)

    def getList(self, stack, res, cnt):
        nodes = []
        flag = True #标记该层是否都是空节点
        if len(stack) == 0:
            return res
        for i in range(0, cnt):
            nodes += [stack.pop(0)]
        newRes = []
        for j in nodes:
            if j == None:
                stack += [None, None]
            else:
                flag = False
                stack += [j.left]
                stack += [j.right]
                newRes += [j.val]
        if not flag:
            res = [newRes] + res
            return self.getList(stack, res, cnt * 2)
        else:
            return res

第一版,应该是正确的,但是会超时。观察了下,有改进的余地。

Code

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

class Solution(object):
    def levelOrderBottom(self, root):
        """
        :type root: TreeNode
        :rtype: List[List[int]]
        """
        stack, res, cnt = [root], [], 1
        while not len(stack) == 0:
            flag = True #标记该层是否都是空节点
            nodes = []
            for i in range(0, cnt):
                node = stack.pop(0)
                if node == None:
                    stack += [None, None]
                else:
                    flag = False
                    stack += [node.left, node.right]
                    nodes += [node.val]
            if flag:
                return res
            else:
                res = [nodes] + res
            cnt *= 2
        return res

第二版,更加精简了,但还是超时。观察了下超时用例,树有很多层,同时很多null,但是我的代码里还是将空节点存到stack里了,所以耗费了时间去处理。下个版本的代码改进点就是从stack中去掉空节点了。

Code

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

class Solution(object):
    def levelOrderBottom(self, root):
        """
        :type root: TreeNode
        :rtype: List[List[int]]
        """
        if root == None:
            return []
        stack, res = [root], []
        while not len(stack) == 0:
            level = []
            temp = []
            for node in stack:
                if not node.left == None:
                    temp += [node.left]
                if not node.right == None:
                    temp += [node.right]
                level += [node.val]
            res = [level] + res
            stack = temp
        return res

这里遇到个debug了很久的问题,当level = temp = []这么初始化的时候一直有bug,结果发现是自己没有掌握清楚语法。a = b = []的时候,a和b指向的是同一个地址,二者谁修改了该处的值,另一方都能读出来。而a = [], b = []这两者就没有关系了。
看了下别人的算法,一种是我这样的BFS,另一种就是DFS,利用二维数组来存储信息。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值