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: TreeNode12 :type L: int13 :type R: int14 :rtype: TreeNode15 """16 if root is None:17 return None18 if root.val >R:19 return self.trimBST(root.left ,L,R)20 if root.val