Leetcode 938:二叉搜尋樹的範圍和(最詳細的解法!!!)
阿新 • • 發佈:2018-11-14
給定二叉搜尋樹的根結點 root
,返回 L
和 R
(含)之間的所有結點的值的和。
二叉搜尋樹保證具有唯一的值。
示例 1:
輸入:root = [10,5,15,3,7,null,18], L = 7, R = 15
輸出:32
示例 2:
輸入:root = [10,5,15,3,7,13,18,1,null,6], L = 6, R = 10
輸出:23
提示:
- 樹中的結點數量最多為
10000
個。 - 最終的答案保證小於
2^31
。
解題思路
這個問題非常簡單。我們首先想到的做法就是,先通過中序遍歷得到中序遍歷陣列,然後遍歷這個陣列得到L
R
的位置,然後計算這兩個位置中所有元素的和即可。
想要如何寫出優雅的中序遍歷,看這篇文章Leetcode 94:二叉樹的中序遍歷(最優雅的解法!!!)
class Solution:
def rangeSumBST(self, root, L, R):
"""
:type root: TreeNode
:type L: int
:type R: int
:rtype: int
"""
tmp,result = list(), 0
self.inorder( root, tmp)
left, right = 0, 0
for i, val in enumerate(tmp):
if val == L:
left = i
if val == R:
right = i
break
return sum(tmp[left:right+1])
def inorder(self, root, result):
if root:
self. helper(root.left, result)
result.append(root.val)
self.helper(root.right, result)
另一種非常簡單的思路就直接遍歷整棵二叉樹,然後對L <= val <= R
的元素做加法。我們這裡使用迭代版本的前序遍歷。
想要如何寫出優雅的前序遍歷,看這篇文章Leetcode 144:二叉樹的前序遍歷(最優雅的解法!!!)
class Solution:
def rangeSumBST(self, root, L, R):
"""
:type root: TreeNode
:type L: int
:type R: int
:rtype: int
"""
result, stack = 0, [root]
while stack:
node = stack.pop()
if node:
if L <= node.val <= R:
result += node.val
if node.val < R:
stack.append(node.right)
if L < node.val:
stack.append(node.left)
return result
還有一種比較簡潔的思路就是直接使用遞迴。我們要知道以root
為根區間在[L,R]
的和,我們只需要知道以root.left
為根區間在[L,root.val-1]
這個區間的元素和加上以root.right
為根區間在[root.val+1,R]
這個區間的元素和再加上root.val
即可。也就是將[L,R]
拆借為[L,root.val-1]
、[root.val]
和[root.val+1, R]
三個區間。
class Solution:
def rangeSumBST(self, root, L, R):
"""
:type root: TreeNode
:type L: int
:type R: int
:rtype: int
"""
if not root or L > R:
return 0
if root.val < L:
return self.rangeSumBST(root.right, L, R)
if root.val > R:
return self.rangeSumBST(root.left, L, R)
return root.val + self.rangeSumBST(root.left, L, root.val - 1)+\
self.rangeSumBST(root.right, root.val + 1, R)
我將該問題的其他語言版本新增到了我的GitHub Leetcode
如有問題,希望大家指出!!!