您的位置:首页 > 其它

LC-Trim a Binary Search Tree

2017-12-19 23:48 246 查看
class TreeNode(object):

def __init__(self,x):
self.val = x
self.left = None
self.right = None

class Solution(object):
def trimBST(self, root, L, R):
"""
:type root: TreeNode
:type L: int
:type R: int
:rtype: TreeNode
"""

if not root:
return None
if L > root.val:
return self.trimBST(root.right, L, R)
elif R < root.val:
return self.trimBST(root.l
4000
eft, L, R)
root.left = self.trimBST(root.left, L, R)
root.right = self.trimBST(root.right, L, R)
return root

Sol = Solution()

t1 = TreeNode(1)
t1.left = TreeNode(0)
t1.tight = TreeNode(2)

ans = Sol.trimBST(t1,1,2)
print ans.val


1,比较简洁的算法

2,对于树的操作,核心在于递归的构造
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: