day 18: 二叉树-补卡

Leetcode 513. Find Bottom Left Tree Value

Problem is find the first element if the bottom layer

class Solution:
    def findBottomLeftValue(self, root: Optional[TreeNode]) -> int:
        # record first element of last layer:
        queue = [root]
        while queue:
            l = len(queue)
            for i in range(l):
                node = queue.pop(0)
                if i == 0 : res = node.val
                if node.left: queue.append(node.left)
                if node.right: queue.append(node.right)
        return res

BFS!!! YYDS!!!

Leetcode 112.Path Sum

class Solution:
    def hasPathSum(self, root: Optional[TreeNode], targetsum: int) -> bool:
        if not root:
            return False

        stack = []  # [(当前节点,路径数值), ...]
        stack.append((root, root.val))

        while stack:
            cur_node, path_sum = stack.pop()

            if not cur_node.left and not cur_node.right and path_sum == targetsum:
                return True

            if cur_node.right:
                stack.append((cur_node.right, path_sum + cur_node.right.val))

            if cur_node.left:
                stack.append((cur_node.left, path_sum + cur_node.left.val))

        return False

把每个节点和该节点的求和状态存储入栈! Nice!

Leetcode 106.Construct Binary Tree from Inorder and Postorder Traversal

好难 会思路也写不出来啊

class Solution:
    def buildTree(self, inorder: List[int], postorder: List[int]) -> Optional[TreeNode]:
        # 第一步: 特殊情况讨论: 树为空. (递归终止条件)
        if not postorder:
            return None

        # 第二步: 后序遍历的最后一个就是当前的中间节点.
        root_val = postorder[-1]
        root = TreeNode(root_val)

        # 第三步: 找切割点.
        separator_idx = inorder.index(root_val)

        # 第四步: 切割inorder数组. 得到inorder数组的左,右半边.
        inorder_left = inorder[:separator_idx]
        inorder_right = inorder[separator_idx + 1:]

        # 第五步: 切割postorder数组. 得到postorder数组的左,右半边.
        # ⭐️ 重点1: 中序数组大小一定跟后序数组大小是相同的.
        postorder_left = postorder[:len(inorder_left)]
        postorder_right = postorder[len(inorder_left): len(postorder) - 1]

        # 第六步: 递归
        root.left = self.buildTree(inorder_left, postorder_left)
        root.right = self.buildTree(inorder_right, postorder_right)

        return root
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值