close
題目:
Given the root node of a binary search tree, return the sum of values of all nodes with a value in the range [low, high].
簡易說明:
給tree,求順序下low到high總和
解法:
排序後從low加總到high即可。
code:
# 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: TreeNode, low: int, high: int) -> int:
nums=[]
def inOrder(root):
if not root:
return
if root.left:
inOrder(root.left)
nums.append(root.val)
if root.right:
inOrder(root.right)
inOrder(root)
addsum=0
for k in range(nums.index(low),nums.index(high)+1):
addsum+=nums[k]
return addsum
文章標籤
全站熱搜
留言列表