代码随想录day18 寻找树左下角 路经总和 构造二叉树

1. 寻找树的左下角 

513. 找树左下角的值 - 力扣(LeetCode) 

1)递归+回溯+栈:这里右侧叶子先入栈,出栈时就是从左叶子开始。若后出栈的(靠右的)叶子具有更大的深度,就用它更新当前结果。

class Solution:
    def reachLeaf(self, node, depth, leaves):
        if not node.right and not node.left:
            leaves.append((node.val, depth))
        
        if node.right:
            self.reachLeaf(node.right, depth + 1, leaves)

        if node.left:
            self.reachLeaf(node.left, depth + 1, leaves)

    def findBottomLeftValue(self, root: Optional[TreeNode]) -> int:
        leaves = []
        self.reachLeaf(root, 1, leaves)
        
        max_d = 0
        res = root.val
        while leaves:
            leaf = leaves.pop()
            val, depth = leaf[0], leaf[1]
            if max_d < depth:
                max_d = depth
                res = val
        
        return res

也可以不用栈而使用两个全局变量,self.res保存当前结果,self.depth保存当前结果对应的深度。注意此时需要先进入左树。

class Solution:
    def func(self, node, depth):
        if not node.left and not node.right:
            if self.depth < depth:
                self.depth = depth
                self.res = node.val
            return

        if node.left:
            self.func(node.left, depth + 1)
        if node.right:
            self.func(node.right, depth + 1)

    def findBottomLeftValue(self, root: Optional[TreeNode]) -> int:
        self.res = root.val
        self.depth = 0
        self.func(root, 1)

        return self.res

2)层序遍历:用一个嵌套列表保存每层的节点,遍历结束后取最后一层的第一个(最左)节点即可。

class Solution:
    def findBottomLeftValue(self, root: Optional[TreeNode]) -> int:
        from collections import deque
        que = deque([root])
        nodes = []

        while que:
            size = len(que)
            tmp = []
            for _ in range(size):
                node = que.popleft()
                tmp.append(node)

                if node.left:
                    que.append(node.left)
                if node.right:
                    que.append(node.right)
            
            nodes.append(tmp)
        
        return nodes[-1][0].val

2. 路径总和 

112. 路径总和 - 力扣(LeetCode) 

递归:辅助函数func(),不对其传入空节点。参数为:node,当前节点;cur:当前节点之前的路径和;tar:目标和。若当前节点为叶子节点而且节点值+cur等于tar,则找到正确的路径,返回true;若为叶子但和不等于tar,则返回false。若不为叶子,继续遍历非空的孩子。若左子树返回结果为true,不用再考虑右子树,直接返回true;否则再接着判断右子树是否存在正确路径。

class Solution:
    def func(self, node, cur, tar):
        if not node.left and not node.right:
            if node.val + cur == tar:
                return True
            return False #not this path
        
        if node.left:
            f1 = self.func(node.left, cur+node.val, tar)
        else:
            f1 = False
        if f1:
            return True #剪枝
        
        if node.right:
            f2 = self.func(node.right, cur+node.val, tar)
        else:
            f2 = False
        
        return f1 or f2

    def hasPathSum(self, root: Optional[TreeNode], targetSum: int) -> bool:
        if not root:
            return False
        
        return self.func(root, 0, targetSum)

更简洁的写法 :

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

        if not root.left and not root.right and root.val == targetSum:
            return True
        
        return self.hasPathSum(root.left, targetSum-root.val) or self.hasPathSum(root.right, targetSum-root.val)

 

113. 路径总和 II - 力扣(LeetCode) 

* 注意列表path不可以直接放入列表res,需要先将其转为不可变的tuple;

* 回溯包括cur和path,注意两者的回溯是如何实现的;

* 需要理清楚传入辅助函数func()的node、cur、path的关系,在这里cur和path是包含当前node的路径和、路径。

class Solution:
    def func(self, node, cur, tar, path, res):
        if not node.left and not node.right:
            if cur == tar:
                res.append(tuple(path)) #若不转为tuple,res会随着path回溯而变化。

            return #到了叶子表面该路径结束,不管该路径是否符合要求,都返回。

        if node.left:
            path.append(node.left.val)
            self.func(node.left, cur+node.left.val, tar, path, res)
            path.pop()
        
        if node.right:
            path.append(node.right.val)
            self.func(node.right, cur+node.right.val, tar, path, res)
            path.pop()

    def pathSum(self, root: Optional[TreeNode], targetSum: int) -> List[List[int]]:
        if not root:
            return []

        path = [root.val]
        res = []
        self.func(root, root.val, targetSum, path, res)

        return res

 

3. 构造二叉树

106. 从中序与后序遍历序列构造二叉树 - 力扣(LeetCode) 

左闭右开,记得每次除掉root。

class Solution:
    def func(self, inorder, postorder, in_b, in_e, post_b, post_e):
        if in_b == in_e:
            return None

        if in_b + 1 == in_e:
            return TreeNode(val=inorder[in_b])

        root_val = postorder[post_e-1]
        root_id = inorder.index(root_val)
        left_in_b, left_in_e = in_b, root_id
        right_in_b, right_in_e = root_id+1, in_e
        left_post_b, left_post_e = post_b, post_b + (root_id - in_b)
        right_post_b, right_post_e = left_post_e, post_e - 1 
        
        root = TreeNode(val = root_val)
        root.left = self.func(inorder, postorder, left_in_b, left_in_e, left_post_b, left_post_e)
        root.right = self.func(inorder, postorder, right_in_b, right_in_e, right_post_b, right_post_e)

        return root


    def buildTree(self, inorder: List[int], postorder: List[int]) -> Optional[TreeNode]:
        if not inorder:
            return None
        size = len(inorder)
        return self.func(inorder, postorder, in_b=0, in_e=size, post_b=0, post_e=size)

105. 从前序与中序遍历序列构造二叉树 - 力扣(LeetCode) 

class Solution:
    def func(self, preorder, inorder, pre_b, pre_e, in_b, in_e):
        if pre_b == pre_e:
            return None

        if pre_b + 1 == pre_e:
            return TreeNode(val = preorder[pre_b])
        
        root_val = preorder[pre_b]
        root_id = inorder.index(root_val)
        left_in_b, left_in_e = in_b, root_id
        right_in_b, right_in_e = root_id + 1, in_e
        left_pre_b, left_pre_e = pre_b + 1, pre_b + 1 + (root_id - in_b)
        right_pre_b, right_pre_e = left_pre_e, pre_e

        root = TreeNode(val = root_val)
        root.left = self.func(preorder, inorder, left_pre_b, left_pre_e, left_in_b, left_in_e)
        root.right = self.func(preorder, inorder, right_pre_b, right_pre_e, right_in_b, right_in_e)

        return root

    def buildTree(self, preorder: List[int], inorder: List[int]) -> Optional[TreeNode]:
        if not preorder:
            return None
        return self.func(preorder, inorder, 0, len(preorder), 0, len(inorder))

654. 最大二叉树 - 力扣(LeetCode) 

思路与上题类似。这里仍用左闭右开。

class Solution:
    def func(self, nums, begin, end):
        if begin == end:
            return None

        root_val = max(nums[begin:end])
        root_id = nums.index(root_val)
        root = TreeNode(val = root_val)
        root.left = self.func(nums, begin, root_id)
        root.right = self.func(nums, root_id+1, end)
        
        return root

    def constructMaximumBinaryTree(self, nums: List[int]) -> Optional[TreeNode]:
        if not nums:
            return None
        
        return self.func(nums, 0, len(nums))

  • 5
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值