代码随想录算法训练营第十六天 | 513.找树左下角的值、112. 路径总和、106.从中序与后序遍历序列构造二叉树

513.找树左下角的值

广搜先right后left, 最后就是左下角了。

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def findBottomLeftValue(self, root: Optional[TreeNode]) -> int:
        que = collections.deque([root])
        while que:
            cur = que.popleft()
            res = cur.val
            if cur.right:
                que.append(cur.right)
            if cur.left:
                que.append(cur.left)
            
        return res

递归稍微麻烦一点,

找左下角就是找某个子树的左下角,这个左下角元素肯定是深度最大的左叶子。

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def findBottomLeftValue(self, root: Optional[TreeNode]) -> int:
        
        def dfs(root):
            left_depth, right_depth = 0, 0
            if not root.left and not root.right:
                return root.val, 1
            if root.left:
                left_val, left_depth = dfs(root.left)
            if root.right:
                right_val, right_depth = dfs(root.right)
            
            if left_depth >= right_depth:
                return left_val, left_depth + 1
            else:
                return right_val, right_depth + 1
        res, _ = dfs(root)
        return res

其实感觉自己这个比题解里面回溯好理解一些...把回溯方法也写一下。

细想了一下之前好多题我的闭包传递方法好像也是回溯?有时间再看下。

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def findBottomLeftValue(self, root: Optional[TreeNode]) -> int:
        self.maxDepth = float('-inf')
        self.result = None
        def dfs(root, depth):
            if not root.left and not root.right:
                if depth > self.maxDepth:
                    self.maxDepth = depth
                    self.result = root.val
                return
            if root.left:
                dfs(root.left, depth + 1)
            if root.right:
                dfs(root.right, depth + 1)
        dfs(root, 0)
        return self.result

112. 路径总和

直接使用回溯模板即可。

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def hasPathSum(self, root: Optional[TreeNode], targetSum: int) -> bool:
        if not root:
            return False
        self.result = False

        def dfs(root, targetSum):
            if not root.left and not root.right:
                if targetSum == root.val:
                    self.result = True
                return
            
            if root.left:
                dfs(root.left, targetSum - root.val)
            if root.right:
                dfs(root.right, targetSum - root.val)

        dfs(root, targetSum)

        return self.result
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def hasPathSum(self, root: Optional[TreeNode], targetSum: int) -> bool:
        if not root:
            return False
        if not root.left and not root.right:
            if targetSum == root.val:
                return True
        return self.hasPathSum(root.left, targetSum - root.val) or self.hasPathSum(root.right, targetSum - root.val)

迭代跳过了。

做一下路径总和ii

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def pathSum(self, root: Optional[TreeNode], targetSum: int) -> List[List[int]]:
        res = []
        path = []
        def dfs(root, targetSum):
            if not root.left and not root.right:
                if targetSum == root.val:
                    res.append(path + [root.val])
                return

            if root.left:
                path.append(root.val)
                dfs(root.left, targetSum - root.val)
                path.pop()
            if root.right:
                path.append(root.val)
                dfs(root.right, targetSum - root.val)
                path.pop()

        if not root:
            return []

        dfs(root,targetSum)
        return res

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

后序的末尾是当前需要构建的二叉树的根节点;

在中序中找到根节点,左边就是左子树右边就是右子树。

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def buildTree(self, inorder: List[int], postorder: List[int]) -> Optional[TreeNode]:
        if not inorder:
            return None
        
        mid = postorder[-1]
        root = TreeNode(mid)
        partition = inorder.index(mid)
        left_partition = inorder[:partition]
        right_partition = inorder[partition + 1:]
        root.left = self.buildTree(left_partition, postorder[:len(left_partition)])
        root.right = self.buildTree(right_partition, postorder[len(left_partition):-1])
        return root

学一下题解优化:

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def buildTree(self, inorder: List[int], postorder: List[int]) -> Optional[TreeNode]:
        
        def build(inorder_start, inorder_end, postorder_start, postorder_end):
            if inorder_start > inorder_end:
                return None
            
            mid = postorder[postorder_end]
            root = TreeNode(mid)
            partition = val_to_index[mid]
            root.left = build(inorder_start, partition - 1, postorder_start, postorder_start + partition - inorder_start - 1)
            root.right = build(partition + 1, inorder_end, postorder_end - inorder_end + partition,postorder_end - 1)
            return root
        n = len(inorder)
        val_to_index = {}
        for i in range(n):
            val_to_index[inorder[i]] = i
        return build(0, n - 1, 0, n - 1)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值