[Leetcode] 669. Trim a Binary Search Tree 解题报告
2018-01-29 12:43
519 查看
题目:
Given a binary search tree and the lowest and highest boundaries as
trim the tree so that all its elements lies in
the root of the tree, so the result should return the new root of the trimmed binary search tree.
Example 1:
Example 2:
思路:
判断根节点的值和[L,R]的关系:如果比L还小,根节点也要被trim,所以返回对左子树的调用即可;如果比R还大,根节点同样要被trim,所以返回对右子树的调用即可。否则根节点就需要保留,所以我们分别trim其左右子树,然后返回根节点。
代码:/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) :
4000
val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* trimBST(TreeNode* root, int L, int R) {
if (root == NULL) {
return NULL;
}
if (root->val < L) {
return trimBST(root->right, L, R);
}
else if (root->val > R) {
return trimBST(root->left, L, R);
}
else {
root->left = trimBST(root->left, L, R);
root->right = trimBST(root->right, L, R);
return root;
}
}
};
Given a binary search tree and the lowest and highest boundaries as
Land
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还小,根节点也要被trim,所以返回对左子树的调用即可;如果比R还大,根节点同样要被trim,所以返回对右子树的调用即可。否则根节点就需要保留,所以我们分别trim其左右子树,然后返回根节点。
代码:/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) :
4000
val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* trimBST(TreeNode* root, int L, int R) {
if (root == NULL) {
return NULL;
}
if (root->val < L) {
return trimBST(root->right, L, R);
}
else if (root->val > R) {
return trimBST(root->left, L, R);
}
else {
root->left = trimBST(root->left, L, R);
root->right = trimBST(root->right, L, R);
return root;
}
}
};
相关文章推荐
- [Leetcode] 235. Lowest Common Ancestor of a Binary Search Tree 解题报告
- 【LeetCode】1. Two Sum 解题报告
- 【LeetCode】Binary Tree Preorder Traversal 解题报告
- [leetcode] 3. Longest Substring Without Repeating Characters 解题报告
- 【LeetCode】303. Range Sum Query - Immutable 解题报告
- 【LeetCode】Balanced Binary Tree 解题报告
- 【LeetCode】28. Implement strStr() 解题报告
- [leetcode] 296. Best Meeting Point 解题报告
- [leetcode] 186. Reverse Words in a String II 解题报告
- [Leetcode] 349. Intersection of Two Arrays 解题报告
- 【LeetCode】763. Partition Labels 解题报告
- 【LeetCode】Construct the Rectangle 解题报告
- 【LeetCode】Longest Palindromic Substring 解题报告
- LeetCode Convert Sorted List to Binary Search Tree 解题报告
- [LeetCode] Edit Distance 解题报告
- Leetcode 393. UTF-8 Validation UTF-8 编码识别 解题报告
- Leetcode 76-MinimumWindowSubstring 解题报告
- [leetcode] 375. Guess Number Higher or Lower II 解题报告
- [LeetCode] Permutations 解题报告
- [LeetCode] Recover Binary Search Tree 解题报告