代码随想录算法训练营第18天| Binary Tree|● 513.找树左下角的值● 112. 路径总和 113.路径总和ii● 106.从中序与后序遍历序列构造二叉树 105.从前序与中序遍历序列

Given the root of a binary tree, return the leftmost value in the last row of the tree.

class Solution:
    def findBottomLeftValue(self, root: Optional[TreeNode]) -> int:
        queue = deque([root])
        while queue:
            size = len(queue)
            level = None
            for _ in range(size):
                node = queue.popleft()
                if level==None:
                    level = node.val
                if node.left:
                    queue.append(node.left)
                if node.right:
                    queue.append(node.right)
        return level

112. Path Sum

Given the root of a binary tree and an integer targetSum, return true if the tree has a root-to-leaf path such that adding up all the values along the path equals targetSum.

A leaf is a node with no children.

xample 1:

img
Input: root = [5,4,8,11,null,13,4,7,2,null,null,null,1], targetSum = 22
Output: true
Explanation: The root-to-leaf path with the target sum is shown.
  • Sol1: 递归
class Solution:
    def hasPathSum(self, root: Optional[TreeNode], targetSum: int) -> bool:
        
        def dfs(node,sum_):
            if not node:
                return False
            sum_ += node.val
            if not node.left and not node.right:
                return sum_ == targetSum
            return dfs(node.left,sum_) or dfs(node.right,sum_)
        return dfs(root,0)

  • Sol2: 递归回溯, same as 257
class Solution1:
    def hasPathSum(self, root: Optional[TreeNode], targetSum: int) -> bool:
        res = []
        path = []

        def backtracking(node):
            if not node:
                return
            path.append(node.val)

            if not node.left and not node.right:
                res.append(sum(path))
            if node.left:
                backtracking(node.left)
                path.pop()
            if node.right:
                backtracking(node.right)
                path.pop()
            return
        backtracking(root)

        if targetSum in res:
            return True
        return False

113 Path Sum II * (回溯模板)

Given the root of a binary tree and an integer targetSum, return all root-to-leaf paths where the sum of the node values in the path equals targetSum. Each path should be returned as a list of the node values, not node references.

A root-to-leaf path is a path starting from the root and ending at any leaf node. A leaf is a node with no children.

class Solution:
    def pathSum(self, root: Optional[TreeNode], targetSum: int) -> List[List[int]]:
        path = []
        res = []
        def backtrack(node,targetSum):
            if not node:
                return
            path.append(node.val)
            if not node.left and not node.right:
                if sum(path) == targetSum:
                    res.append(path[:]) #!! copy the whole list, otherwise only a pointer
                    #print("res:",res)
                return
            if node.left:
                backtrack(node.left,targetSum)
                path.pop()
            if node.right:
                backtrack(node.right,targetSum)
                path.pop()
            return

        backtrack(root,targetSum)
        return res
  • res.append(path[:])

106. Construct Binary Tree from Inorder and Postorder Traversal 构造二叉树

Given two integer arrays inorder and postorder where inorder is the inorder traversal of a binary tree and postorder is the postorder traversal of the same tree, construct and return the binary tree

Example 1:

img
Input: inorder = [9,3,15,20,7], postorder = [9,15,7,20,3]
Output: [3,9,20,null,null,15,7]
class Solution:
    def buildTree(self, inorder: List[int], postorder: List[int]) -> Optional[TreeNode]:
        if not inorder:
            return None

        root_val = postorder[-1]
        root = TreeNode(root_val)
        root_idx_in = inorder.index(root_val)
 
        in_left, in_right = inorder[:root_idx_in], inorder[root_idx_in+1:]
        post_left,post_right = postorder[:len(in_left)],postorder[len(in_left):-1]

        root.left = self.buildTree(in_left,post_left)
        root.right = self.buildTree(in_right,post_right)

        return root

  • postorder the last one is root
  • inorder find the root, then left|root|right cut
  • from inorder left/right size, get postoder left|right|root cut
  • recurrent, set root.left, root.right
  • if inorder (postorder) is empty, it is the leaf node’s children, return None
    • inorder size == postorder size

105. Construct Binary Tree from Preorder and Inorder Traversal 构造二叉树

class Solution:
    def buildTree(self, preorder: List[int], inorder: List[int]) -> Optional[TreeNode]:
        if not preorder:
            return None
        
        root_val = preorder[0]
        root = TreeNode(root_val)
        root_idx_in = inorder.index(root_val)
        in_left, in_right = inorder[:root_idx_in], inorder[root_idx_in+1:]
        pre_left, pre_right = preorder[1:len(in_left)+1], preorder[1+len(in_left):]

        root.left, root.right = self.buildTree(pre_left,in_left), self.buildTree(pre_right,in_right)

        return root

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值