leetcode算法:Trim a Binar Search Tree

Given a binary search tree and the lowest and highest boundaries as L and R, trim the tree so that all its elements lies in [L, R] (R >= L). You might need to change the root of the tree, so the result should return the new root of the trimmed binary search tree.

Example 1:
Input:
1
/
0 2

L = 1
R = 2

Output:
1

2
Example 2:
Input:
3
/
0 4

2
/
1

L = 1
R = 3

Output:
3
/
2
/
1


这道题描述的需求是:
给我们一个二叉排序树 最小数l 和最大数r
我们需要做的是对这棵树进行裁剪,让树里所有的节点值都满足在l和r之间

思想:
二叉排序树的特点是:对于任意一个节点,左子树任意节点数值都比跟节点小,右子树任意节点数值都比根大
所以考虑,对于任意一个节点,
如果值比l还小,那就应该抛弃这个根,去右子树寻找新的根
如果值比r还大,那就应该抛弃这个根,去左子树寻找新的根

这样的操作进行递归就可以了

我的python代码:

 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         """
16         if root is None:
17             return None
18         if root.val >R:
19             return self.trimBST(root.left ,L,R)
20         if root.val<L:
21             return self.trimBST(root.right, L, R)
22         root.left = self.trimBST(root.left,L,R)
23         root.right = self.trimBST(root.right,L,R)
24         return root
25 
26 
27 
28 if __name__ == '__main__':
29     s = Solution()
30 
31     root = TreeNode(1)
32     root.left = TreeNode(0)
33     root.right = TreeNode(2)
34 
35     print(root.val,root.left.val,root.right.val)
36 
37     root = s.trimBST(root,1,2)
38 
39     print(root, root.left, root.right)








原文地址:https://www.cnblogs.com/Lin-Yi/p/7501855.html