1. 程式人生 > >leetcode算法:Trim a Binar Search Tree

leetcode算法:Trim a Binar Search Tree

ret ear elf med tput fin pri treenode __main__

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)









leetcode算法:Trim a Binar Search Tree