LeetCode: 669 Trim a Binary Search Tree(easy)
题目:
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
代码:
二叉查找树(英语:Binary Search Tree),也称二叉搜索树、有序二叉树(英语:ordered binary tree),排序二叉树(英语:sorted binary tree),是指一棵空树或者具有下列性质的二叉树:
- 若任意节点的左子树不空,则左子树上所有节点的值均小于它的根节点的值;
- 若任意节点的右子树不空,则右子树上所有节点的值均大于它的根节点的值;
- 任意节点的左、右子树也分别为二叉查找树;
- 没有键值相等的节点。
使用递归:
1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution { 11 public: 12 TreeNode* trimBST(TreeNode* root, int L, int R) { 13 if(!root) 14 return root; 15 if(root->val>=L && root->val<=R) { 16 root->left = trimBST(root->left, L, R); 17 root->right = trimBST(root->right, L, R); 18 } 19 else if(root->val > R) { 20 root->left = trimBST(root->left, L, R); 21 root=root->left; 22 } 23 else { 24 root->right = trimBST(root->right, L, R); 25 root=root->right; 26 } 27 return root; 28 } 29 };