代码随想录算法训练营第18天

513. 找树左下角的值

class Solution:
    def __init__(self):
        self.max_depth = -1
        self.val = 0
    def findBottomLeftValue(self, root: Optional[TreeNode]) -> int:
        if not root:return
        self.dfs(root,0)
        return self.val
    def dfs(self,root,cur_depth):
        if not root.left and not root.right:
            if cur_depth > self.max_depth:
                self.max_depth = cur_depth
                self.val = root.val
        if root.left:
            cur_depth +=1
            self.dfs(root.left,cur_depth)
            cur_depth -=1
        if root.right:
            cur_depth +=1
            self.dfs(root.right,cur_depth)
            cur_depth -=1

112. 路径总和

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

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

class Solution:
    def buildTree(self, inorder: List[int], postorder: List[int]) -> Optional[TreeNode]:
        if not postorder: return
        root_val = postorder[-1]
        root = TreeNode(root_val)
        sep_index = inorder.index(root.val)
        in_left = inorder[:sep_index]
        in_right = inorder[sep_index+1:]
        po_left = postorder[:len(in_left)]
        po_right = postorder[len(in_left):len(postorder)-1]
        root.left = self.buildTree(in_left, po_left)
        root.right = self.buildTree(in_right, po_right)
        return root

你可能感兴趣的:(python)