Skip to content

add leetcode Trim a Binary Search Tree #1156

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions leetcode/DIRECTORY.md
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,7 @@
| 561 | [Array Partition I](https://leetcode.com/problems/array-partition-i/) | [C](./src/561.c) | Easy |
| 617 | [Merge Two Binary Trees](https://leetcode.com/problems/merge-two-binary-trees/) | [C](./src/617.c) | Easy |
| 647 | [Palindromic Substring](https://leetcode.com/problems/palindromic-substrings/) | [C](./src/647.c) | Medium |
| 669 | [Trim a Binary Search Tree](https://leetcode.com/problems/trim-a-binary-search-tree/) | [C](./src/669.c) | Medium |
| 674 | [Longest Continuous Increasing Subsequence](https://leetcode.com/problems/longest-continuous-increasing-subsequence/) | [C](./src/674.c) | Easy |
| 700 | [Search in a Binary Search Tree](https://leetcode.com/problems/search-in-a-binary-search-tree/) | [C](./src/700.c) | Easy |
| 701 | [Insert into a Binary Search Tree](https://leetcode.com/problems/insert-into-a-binary-search-tree/) | [C](./src/701.c) | Medium |
Expand Down
30 changes: 30 additions & 0 deletions leetcode/src/669.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/


// Depth-First Search
// Runtime: O(n)
// Space: O(1)
struct TreeNode* trimBST(struct TreeNode* root, int low, int high){
if (root == NULL){
return NULL;
}

if (root->val > high){
return trimBST(root->left, low, high);
}

if (root->val < low){
return trimBST(root->right, low, high);
}

root->left = trimBST(root->left, low, high);
root->right = trimBST(root->right, low, high);
return root;
}