938. 二叉搜尋樹的範圍和
阿新 • • 發佈:2019-01-04
思路: 明確二叉搜尋樹的性質。按中序遍歷後得到的陣列是升序排列的。
L和R中間的數其實也相當於[L, R]之間的數。這樣有幾種方法可以得到:
注意: root = [10, 5, 15, 3, 7, 13, 18, 1, null, 6]
是按層從左到右給出的。
方法一、直接遍歷二叉樹,遍歷過程中直接把[L, R]之間的數相加。
遍歷條件: if node.val < R: stack.append(node.right) if node.val > L: stack.append(node.left)
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def rangeSumBST(self, root, L, R): """ :type root: TreeNode :type L: int :type R: int :rtype: int """ res, stack = 0, [root] while stack: node = stack.pop() if node: # 只考慮不為空的節點 if L<=node.val<=R: res += node.val if node.val < R: stack.append(node.right) if node.val > L: stack.append(node.left) return res
方法二、中序遍歷後得到有序陣列,再次遍歷得到L和R的位置,將位置間的數字想加。
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def rangeSumBST(self, root, L, R): """ :type root: TreeNode :type L: int :type R: int :rtype: int """ global result result = [] res = self.inorder(root) left = right = 0 for i, val in enumerate(res): if val == L: left = i elif val == R: right = i break return sum(res[left:right+1]) def inorder(self, root): if root is None: return self.inorder(root.left) result.append(root.val) self.inorder(root.right) return result
中間參考了:https://blog.csdn.net/qq_17550379/article/details/84034131