Skip to content

Commit 77b1ded

Browse files
solves trim a binary search tree
1 parent ebcf450 commit 77b1ded

File tree

3 files changed

+27
-1
lines changed

3 files changed

+27
-1
lines changed

README.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -172,7 +172,7 @@
172172
| 657 | [Robot Return to Origin](https://leetcode.com/problems/robot-return-to-origin) | [![Java](assets/java.png)](src/RobotReturnToOrigin.java) [![Python](assets/python.png)](python/robot_return_to_origin.py) |
173173
| 661 | [Image Smoother](https://leetcode.com/problems/image-smoother) | [![Java](assets/java.png)](src/ImageSmoother.java) [![Python](assets/python.png)](python/image_smoother.py) |
174174
| 665 | [Non Deceasing Array](https://leetcode.com/problems/non-decreasing-array) | [![Java](assets/java.png)](src/NonDecreasingArray.java) [![Python](assets/python.png)](python/non_decreasing_array.py) |
175-
| 669 | [Trim a Binary Search Tree](https://leetcode.com/problems/trim-a-binary-search-tree) | |
175+
| 669 | [Trim a Binary Search Tree](https://leetcode.com/problems/trim-a-binary-search-tree) | [![Java](assets/java.png)](src/TrimABinarySearchTree.java) [![Python](assets/python.png)](python/trim_a_binary_search_tree.py) |
176176
| 671 | [Second Minimum Node in Binary Tree](https://leetcode.com/problems/second-minimum-node-in-a-binary-tree) | |
177177
| 674 | [Longest Continuous Increasing Subsequence](https://leetcode.com/problems/longest-continuous-increasing-subsequence) | |
178178
| 680 | [Valid Palindrome II](https://leetcode.com/problems/valid-palindrome-ii) | |

python/trim_a_binary_search_tree.py

+16
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
# Definition for a binary tree node.
2+
class TreeNode:
3+
def __init__(self, val=0, left=None, right=None):
4+
self.val = val
5+
self.left = left
6+
self.right = right
7+
8+
9+
class Solution:
10+
def trimBST(self, root: TreeNode, low: int, high: int) -> TreeNode:
11+
if root is None: return None
12+
if root.val < low: return self.trimBST(root.right, low, high)
13+
if root.val > high: return self.trimBST(root.left, low, high)
14+
root.left = self.trimBST(root.left, low, high)
15+
root.right = self.trimBST(root.right, low, high)
16+
return root

src/TrimABinarySearchTree.java

+10
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
public class TrimABinarySearchTree {
2+
public TreeNode trimBST(TreeNode root, int low, int high) {
3+
if (root == null) return null;
4+
if (root.val < low) return trimBST(root.right, low, high);
5+
if (root.val > high) return trimBST(root.left, low, high);
6+
root.left = trimBST(root.left, low, high);
7+
root.right = trimBST(root.right, low, high);
8+
return root;
9+
}
10+
}

0 commit comments

Comments
 (0)