-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path669.py
64 lines (47 loc) · 1.65 KB
/
669.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# leetcode 669 修剪二叉搜索树
# 第一种 递归法
# 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 trimBST(self, root: Optional[TreeNode], low: int, high: int) -> Optional[TreeNode]:
if not root:
return root
if root.val < low:
return self.trimBST(root.right, low, high)
if root.val > high:
return self.trimBST(root.left, low, high)
root.left = self.trimBST(root.left, low, high)
root.right = self.trimBST(root.right, low, high)
return root
# 第二种 迭代法
# 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 trimBST(self, root: Optional[TreeNode], low: int, high: int) -> Optional[TreeNode]:
if not root:
return root
# 先用一个while把界限控制下来
while root and (root.val < low or root.val > high):
if root.val < low:
root = root.right
else:
root = root.left
cur = root
while cur:
while cur.left and cur.left.val < low:
cur.left = cur.left.right
cur = cur.left
cur = root
while cur:
while cur.right and cur.right.val > high:
cur.right = cur.right.left
cur = cur.right
return root