|
1 | | -// Time: O(n) |
2 | | -// Space: O(h) |
| 1 | +# Time: O(n) |
| 2 | +# Space: O(h) |
3 | 3 |
|
4 | | -/** |
5 | | - * Definition for a binary tree node. |
6 | | - * struct TreeNode { |
7 | | - * int val; |
8 | | - * TreeNode *left; |
9 | | - * TreeNode *right; |
10 | | - * TreeNode(int x) : val(x), left(NULL), right(NULL) {} |
11 | | - * }; |
12 | | - */ |
13 | | -class Solution { |
14 | | -public: |
15 | | - TreeNode* trimBST(TreeNode* root, int L, int R) { |
16 | | - if (!root) { |
17 | | - return nullptr; |
18 | | - } |
19 | | - if (root->val < L) { |
20 | | - return trimBST(root->right, L, R); |
21 | | - } |
22 | | - if (root->val > R) { |
23 | | - return trimBST(root->left, L, R); |
24 | | - } |
25 | | - root->left = trimBST(root->left, L, R); |
26 | | - root->right = trimBST(root->right, L, R); |
27 | | - return root; |
28 | | - } |
29 | | -}; |
| 4 | +# Given a binary search tree and the lowest and highest boundaries as L and R, |
| 5 | +# trim the tree so that all its elements lies in [L, R] (R >= L). |
| 6 | +# You might need to change the root of the tree, so the result should |
| 7 | +# return the new root of the trimmed binary search tree. |
| 8 | +# |
| 9 | +# Example 1: |
| 10 | +# Input: |
| 11 | +# 1 |
| 12 | +# / \ |
| 13 | +# 0 2 |
| 14 | +# |
| 15 | +# L = 1 |
| 16 | +# R = 2 |
| 17 | +# |
| 18 | +# Output: |
| 19 | +# 1 |
| 20 | +# \ |
| 21 | +# 2 |
| 22 | +# Example 2: |
| 23 | +# Input: |
| 24 | +# 3 |
| 25 | +# / \ |
| 26 | +# 0 4 |
| 27 | +# \ |
| 28 | +# 2 |
| 29 | +# / |
| 30 | +# 1 |
| 31 | +# |
| 32 | +# L = 1 |
| 33 | +# R = 3 |
| 34 | +# |
| 35 | +# Output: |
| 36 | +# 3 |
| 37 | +# / |
| 38 | +# 2 |
| 39 | +# / |
| 40 | +# 1 |
| 41 | + |
| 42 | +# Definition for a binary tree node. |
| 43 | +# class TreeNode(object): |
| 44 | +# def __init__(self, x): |
| 45 | +# self.val = x |
| 46 | +# self.left = None |
| 47 | +# self.right = None |
| 48 | + |
| 49 | +class Solution(object): |
| 50 | + def trimBST(self, root, L, R): |
| 51 | + """ |
| 52 | + :type root: TreeNode |
| 53 | + :type L: int |
| 54 | + :type R: int |
| 55 | + :rtype: TreeNode |
| 56 | + """ |
| 57 | + if not root: |
| 58 | + return None |
| 59 | + if root.val < L: |
| 60 | + return self.trimBST(root.right, L, R) |
| 61 | + if root.val > R: |
| 62 | + return self.trimBST(root.left, L, R) |
| 63 | + root.left, root.right = self.trimBST(root.left, L, R), self.trimBST(root.right, L, R) |
| 64 | + return root |
| 65 | + |
0 commit comments