2023.6.16
这个递归的逻辑比较复杂
当当前val大于high时,返还其左子树剪枝后的结果(因为并不能保证左子树全部都能要)
class Solution:
def trimBST(self, root: Optional[TreeNode], low: int, high: int) -> Optional[TreeNode]:
if not root:
return
if root.val > high:
return self.trimBST(root.left, low, high)
elif root.val < low:
return self.trimBST(root.right, low, high)
root.left = self.trimBST(root.left, low, high)
root.right = self.trimBST(root.right, low, high)
return root
自写
getin的功能是给定根节点,从根节点开始遍历,直到找到节点的值在low与high之间,以此节点为新的根节点,其他节点全部都舍弃掉(因为这个过程像是在找low与high的最近公共祖先,所以叫getin)
然而根节点在low与high之间并不能保证其子节点也全部满足,因此要继续遍历。
cutit的功能是从getin得到的跟节点开始递归。
class Solution:
def trimBST(self, root: Optional[TreeNode], low: int, high: int) -> Optional[TreeNode]:
self.low = low
self.high = high
root = self.getin(root)
return self.cutit(root)
def getin(self, root): # 初步裁剪,确保根节点一定在[low与high]
if not root:
return None
if self.low <= root.val <=self.high:
return root
if root.val > self.high:
return self.getin(root.left)
else:
return self.getin(root.right)
def cutit(self, root):
if not root: return None
if root.val > self.high:
root.right = None
root.left = self.cutit(self.getin(root.left))
elif root.val < self.low:
root.left = None
root.right = self.cutit(self.getin(root.right))
root.left = self.cutit(self.getin(root.left))
root.right = self.cutit(self.getin(root.right))
return root