Trim a Binary 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.
思路:
采用递归,直到该节点不存在。同时我们需要把该节点值大于R或小于L的清除出去
代码:
1 # Definition for a binary tree node. 2 # class TreeNode(object): 3 # def __init__(self, x): 4 # self.val = x 5 # self.left = None 6 # self.right = None 7 8 class Solution(object): 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 17 if not root: return None 18 19 if root.val < L: return self.trimBST(root.right, L, R) 20 if root.val > R: return self.trimBST(root.left, L, R) 21 22 root.left = self.trimBST(root.left, L, R) 23 root.right = self.trimBST(root.right, L, R) 24 25 return root
感受:
在第一次编写代码时,我将两个if语句返回None,但是是错误的,因为有可能如果该节点的左右孩子都存在且都不符合[L,R],此时该节点左右都为None,执行到这里就要结束了,但存在该节点的子节点的子节点属于[L,R]的情况