LeetCode|938. Range Sum of BST

.

序言

开启python刷题时代,主要也是为了面试。

.

题目

Given the root node of a binary search tree and two integers low and high, return the sum of values of all nodes with a value in the inclusive range [low, high].

Example 1:

  • Input: root = [10,5,15,3,7,null,18], low = 7, high = 15
  • Output: 32
  • Explanation: Nodes 7, 10, and 15 are in the range [7, 15]. 7 + 10 + 15 = 32.

Example 2:

  • Input: root = [10,5,15,3,7,13,18,1,null,6], low = 6, high = 10
  • Output: 23
  • Explanation: Nodes 6, 7, and 10 are in the range [6, 10]. 6 + 7 + 10 = 23.

Constraints:

  • The number of nodes in the tree is in the range [1, 2 * 104].
  • 1 <= Node.val <= 105
  • 1 <= low <= high <= 105
  • All Node.val are unique.

.

思路

简单的树遍历问题,可以用DFS也可以用BFS。
都是第一次用python写,决定先用DFS试试。

DFS遍历树节点,判断每个节点的val是否大于low并且小于high。

.

代码

# 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 rangeSumBST(self, root: Optional[TreeNode], low: int, high: int) -> int:
        def sumVal(root):
            return root.val if low <= root.val <= high else 0
        
        def searchTree(root):
            if root is None:
                return 0
            return sumVal(root) + searchTree(root.left) + searchTree(root.right)

        return searchTree(root)

.

后序

python和C++的语法差异比我想象中的大一些。
目前感觉确实要容易很多。
继续加油!

.

相关推荐

  1. LeetCode938. Range Sum of BST

    2024-06-07 13:14:01       30 阅读
  2. LeetCode968. Binary Tree Cameras

    2024-06-07 13:14:01       48 阅读
  3. LeetCode //C - 933. Number of Recent Calls

    2024-06-07 13:14:01       57 阅读
  4. Leetcode 931. Minimum Falling Path Sum

    2024-06-07 13:14:01       38 阅读
  5. LeetCode 968.监控二叉树 (hard)

    2024-06-07 13:14:01       51 阅读
  6. leetcode93. 复原 IP 地址

    2024-06-07 13:14:01       49 阅读

最近更新

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

    2024-06-07 13:14:01       99 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-06-07 13:14:01       107 阅读
  3. 在Django里面运行非项目文件

    2024-06-07 13:14:01       90 阅读
  4. Python语言-面向对象

    2024-06-07 13:14:01       98 阅读

热门阅读

  1. 什么情况下需要进行网络安全等级保护?

    2024-06-07 13:14:01       33 阅读
  2. 如何将 Vue 应用程序部署到 Cloudflare Pages

    2024-06-07 13:14:01       27 阅读
  3. MySQL8.0默认TCP端口介绍

    2024-06-07 13:14:01       30 阅读
  4. Inner-IoU

    Inner-IoU

    2024-06-07 13:14:01      66 阅读
  5. PLM 解决方案如何提高您的业务效率?

    2024-06-07 13:14:01       30 阅读
  6. ffmplay 源码解读

    2024-06-07 13:14:01       20 阅读
  7. MySQL清空所有表的数据的方法

    2024-06-07 13:14:01       26 阅读
  8. Python里cv2是什么包?怎么安装使用?

    2024-06-07 13:14:01       28 阅读
  9. VBA实战(Excel)(4):实用功能整理

    2024-06-07 13:14:01       28 阅读