Skip to content

Commit e8c45c2

Browse files
authored
Create 669. Trim a Binary Search Tree.py
1 parent 1d5734e commit e8c45c2

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
# Definition for a binary tree node.
2+
# class TreeNode:
3+
# def __init__(self, x):
4+
# self.val = x
5+
# self.left = None
6+
# self.right = None
7+
8+
class Solution:
9+
def trimBST(self, root, L, R):
10+
"""
11+
:type root: TreeNode
12+
:type L: int
13+
:type R: int
14+
:rtype: TreeNode
15+
每一层的Condition有三种:
16+
root.val小于区间的lower bound L,则返回root.right subtree传上来的root,
17+
这里就变相的'删除'掉了当前root和所有root.left的node
18+
root.val大于区间的upper bound R,则返回root.left subtree传上来的root
19+
满足区间,则继续递归
20+
当递归走到叶子节点的时候,我们向上返回root,这里return root的定义是:
21+
返回给parent一个区间调整完以后的subtree
22+
"""
23+
24+
if not root:
25+
return root:
26+
27+
if root.val < L :
28+
return self.trimBST(root.right, L, R)
29+
30+
if root.val > R:
31+
return self.trimBST(root.left, L, R)
32+
33+
root.left = self.trimBST(root.left, L, R)
34+
root.right = self.trimBST(root.right, L, R)
35+
36+
return root
37+
38+

0 commit comments

Comments
 (0)