✅DAY16二叉树续 | 513.找树左下角的值 | 112. 路径总和 | 106.从中序与后序遍历序列构造二叉树

513.找树左下角的值

解题思路:迭代法比较直接

class Solution:
    def findBottomLeftValue(self, root: Optional[TreeNode]) -> int:
        if not root: return 0
        queue = collections.deque([root])
        result = 0
        while queue:
            for i in range(len(queue)):
                node = queue.popleft()
                # i==0是queue里最左侧的值
                if i == 0:
                    result = node.val
                if node.left:
                    queue.append(node.left)
                if node.right:
                    queue.append(node.right)
        return result

解题思路:递归法,找到深度最深的位置,把最左侧的值储存

隐藏回溯:回溯过程通过递归的调用栈隐式实现。因为 depth 是在递归调用时通过参数传递的,因此不需要手动恢复 depth,每次递归调用都会创建一个新的 depth 变量副本,递归返回时自动恢复到上一层。

class Solution:
    def findBottomLeftValue(self, root: Optional[TreeNode]) -> int:
        self.max_depth = float('-inf')
        self.result = None
        self.traversal(root,0)
        return self.result
        
    def traversal(self, node, depth):
        if not node: return
        # 当前是叶子节点
        if not node.left and not node.right:
            if depth > self.max_depth:
                self.max_depth = depth
                self.result = node.val
        # 遍历左子树
        if node.left:
            depth += 1
            self.traversal(node.left, depth)
            depth -= 1
            # 隐藏回溯过程,把参数隐藏在递归过程中,并为实际改变值
            # self.traversal(node.left, depth+1)
        # 遍历右子树
        if node.right:
            depth += 1
            self.traversal(node.right, depth)
            depth -= 1
            # self.traversal(node.right, depth+1)

112. 路径总和

解题思路:递归法,track累计和;网站给的是剩余值和当前node.val进行判断

class Solution:
    def hasPathSum(self, root: Optional[TreeNode], targetSum: int) -> bool:
        def dfs(node, curSum):
            if not node:
                return False
            curSum += node.val
            if not node.left and not node.right:
                return curSum == targetSum
            return (dfs(node.left, curSum) or dfs(node.right, curSum))
        return dfs(root, 0)

解题思路:迭代法

class Solution:
    def hasPathSum(self, root: Optional[TreeNode], targetSum: int) -> bool:
        if not root: return False
        stack = [(root, root.val)]
        while stack:
            node, curSum = stack.pop()
            if not node.left and not node.right and curSum == targetSum:
                return True
            if node.left:
                stack.append((node.left, curSum + node.left.val))
            if node.right:
                stack.append((node.right, curSum + node.right.val))
        return False

106.从中序与后序遍历序列构造二叉树

解题思路:根据中序:左中右+后序:左右中的特性,先用后序把中找到,用中在中序把左中右切割

实现步骤

1. 确定根节点为后序遍历数组的最后一个元素。

2. 在中序遍历数组中找到根节点的位置,将数组分为左右子树部分。

3. 递归地用子数组构建左右子树。

4. 每次递归时更新中序和后序数组的范围。

class Solution:
    def buildTree(self, inorder: List[int], postorder: List[int]) -> Optional[TreeNode]:
        if not inorder or not postorder:
            return None  # 当遍历到空数组时,返回 None,表示该子树不存在
        
        # 后序遍历的最后一个元素是根节点
        root_val = postorder.pop()
        root = TreeNode(root_val)  # 创建根节点
        
        # 找到根节点在中序遍历中的索引位置
        index = inorder.index(root_val)
        
        # 递归构建右子树和左子树
        root.right = self.buildTree(inorder[index + 1:], postorder)  # 右子树部分
        root.left = self.buildTree(inorder[:index], postorder)  # 左子树部分
        
        return root  # 返回当前构建的树的根节点

105. 从前序与中序遍历序列构造二叉树

class Solution:
    def buildTree(self, preorder: List[int], inorder: List[int]) -> Optional[TreeNode]:
        if not preorder or not inorder:
            return None
        
        # 前序遍历的第一个元素是根节点
        root_val = preorder.pop(0)
        root = TreeNode(root_val)
        
        # 在中序遍历中找到根节点的位置
        index = inorder.index(root_val)
        
        # 递归构建左子树和右子树
        # 左子树的中序遍历部分为 inorder[:index]
        # 左子树的前序遍历部分为 preorder[0:index]
        root.left = self.buildTree(preorder, inorder[:index])
        
        # 右子树的中序遍历部分为 inorder[index + 1:]
        # 右子树的前序遍历部分为 preorder[index:]
        root.right = self.buildTree(preorder, inorder[index + 1:])
        
        return root
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值