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

513.找树左下角的值

迭代法比较简单,层序遍历,找到最下面一层的第一个节点。题目已经说明节点数>=1了

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

递归法

题解中遇到叶子节点并且当前深度比最大深度更大时更换结果值,但是最深的节点必定是叶子节点,所以不必判断是叶子节点

class Solution:
    def __init__(self):
        self.result = 0
        self.max_depth = 0

    def findBottomLeftValue(self, root: Optional[TreeNode]) -> int:
        self.getValue(root, 1)
        return self.result

    def getValue(self, node, depth):
        if not node:
            return
        if depth > self.max_depth:
            self.max_depth = depth
            self.result = node.val
        self.getValue(node.left, depth+1)
        self.getValue(node.right, depth+1)

112. 路径总和

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

    def traversal(self, node, cur_sum, target_sum):
        if not node:
            return False
        cur_sum += node.val
        if not node.left and not node.right:
            if cur_sum == target_sum:
                return True
        return self.traversal(node.left, cur_sum, target_sum) or self.traversal(node.right, cur_sum, target_sum)

下面的代码思路更清晰
不要去累加然后判断是否等于目标和,那么代码比较麻烦,可以用递减,让计数器count初始为目标和,然后每次减去遍历路径节点上的数值。
class Solution:
    def hasPathSum(self, root: Optional[TreeNode], targetSum: int) -> bool:
        if not root:
            return False
        return self.traversal(root, targetSum-root.val)

    def traversal(self, node, count):
        if not node.left and not node.right:
            return count == 0
        if node.left:
            if self.traversal(node.left, count-node.left.val):
                return True
        if node.right:
            if self.traversal(node.right, count-node.right.val):
                return True
        return False

路径总和:返回是否存在路径

路径总和II:返回满足条件的所有路径

下面为路径总和II的代码

class Solution:
    def pathSum(self, root: Optional[TreeNode], targetSum: int) -> List[List[int]]:
        result = []
        if not root:
            return result
        self.getPath(root, [root.val], result, targetSum-root.val)
        return result

    def getPath(self, node, path, result, count):
        if not node.left and not node.right:
            if count == 0:
                result.append(path[:])
        if node.left:
            path.append(node.left.val)
            self.getPath(node.left, path, result, count-node.left.val)
            path.pop()
        if node.right:
            path.append(node.right.val)
            self.getPath(node.right, path, result, count-node.right.val)
            path.pop()

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

下面为每层递归定义了新的vector(就是数组),既耗时又耗空间。可以使用索引的方式,每次确定区间的左右索引

class Solution:
    def buildTree(self, inorder: List[int], postorder: List[int]) -> Optional[TreeNode]:
        if len(inorder) <= 0:
            return
        value = postorder[-1]
        index = inorder.index(value)
        left = self.buildTree(inorder[0:index], postorder[0:index])
        right = self.buildTree(inorder[index+1:], postorder[index:-1])
        return TreeNode(value, left, right)

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

class Solution:
    def buildTree(self, preorder: List[int], inorder: List[int]) -> Optional[TreeNode]:
        if not preorder:
            return
        value = preorder[0]
        index = inorder.index(value)
        left = self.buildTree(preorder[1:index+1], inorder[0:index])
        right = self.buildTree(preorder[index+1:], inorder[index+1:])
        return TreeNode(value, left, right)

相关推荐

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-05-14 18:34:07       91 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-05-14 18:34:07       97 阅读
  3. 在Django里面运行非项目文件

    2024-05-14 18:34:07       78 阅读
  4. Python语言-面向对象

    2024-05-14 18:34:07       88 阅读

热门阅读

  1. js 文档片段 DocumentFragment

    2024-05-14 18:34:07       35 阅读
  2. 深度学习关键概念理解

    2024-05-14 18:34:07       28 阅读
  3. rust类型和变量(二)

    2024-05-14 18:34:07       29 阅读
  4. 一个长期后台运行的服务

    2024-05-14 18:34:07       34 阅读
  5. NLP(15)-序列标注任务

    2024-05-14 18:34:07       22 阅读
  6. 单链表与双链表

    2024-05-14 18:34:07       25 阅读
  7. 蓝桥杯单片机组——国赛1 各模块的基础模板

    2024-05-14 18:34:07       29 阅读
  8. 微信小程序-禁止页面下拉回弹

    2024-05-14 18:34:07       31 阅读
  9. Frida逆向与利用自动化

    2024-05-14 18:34:07       33 阅读