mirror of
https://github.com/TheAlgorithms/C
synced 2024-11-25 06:49:36 +03:00
feat: add Kth Smallest Element in a BST (#1157)
Co-authored-by: David Leal <halfpacho@gmail.com>
This commit is contained in:
parent
bf94aff668
commit
496e012c70
@ -61,6 +61,7 @@
|
||||
| 217 | [Contains Duplicate](https://leetcode.com/problems/contains-duplicate/) | [C](./src/217.c) | Easy |
|
||||
| 223 | [Rectangle Area](https://leetcode.com/problems/rectangle-area/) | [C](./src/223.c) | Medium |
|
||||
| 226 | [Invert Binary Tree](https://leetcode.com/problems/invert-binary-tree/) | [C](./src/226.c) | Easy |
|
||||
| 230 | [Kth Smallest Element in a BST](https://leetcode.com/problems/kth-smallest-element-in-a-bst/) | [C](./src/230.c) | Medium |
|
||||
| 231 | [Power of Two](https://leetcode.com/problems/power-of-two/) | [C](./src/231.c) | Easy |
|
||||
| 234 | [Palindrome Linked List](https://leetcode.com/problems/palindrome-linked-list/) | [C](./src/234.c) | Easy |
|
||||
| 242 | [Valid Anagram](https://leetcode.com/problems/valid-anagram/) | [C](./src/242.c) | Easy |
|
||||
|
35
leetcode/src/230.c
Normal file
35
leetcode/src/230.c
Normal file
@ -0,0 +1,35 @@
|
||||
/**
|
||||
* Definition for a binary tree node.
|
||||
* struct TreeNode {
|
||||
* int val;
|
||||
* struct TreeNode *left;
|
||||
* struct TreeNode *right;
|
||||
* };
|
||||
*/
|
||||
|
||||
struct TreeNode* findKthSmallest(struct TreeNode* node, int* k){
|
||||
if (node == NULL){
|
||||
return NULL;
|
||||
}
|
||||
|
||||
struct TreeNode* resultNode = findKthSmallest(node->left, k);
|
||||
|
||||
if (resultNode != NULL){
|
||||
return resultNode;
|
||||
}
|
||||
|
||||
*k -= 1;
|
||||
|
||||
if (*k == 0){
|
||||
return node;
|
||||
}
|
||||
|
||||
return findKthSmallest(node->right, k);
|
||||
}
|
||||
|
||||
// Depth-First Search
|
||||
// Runtime: O(n)
|
||||
// Space: O(1)
|
||||
int kthSmallest(struct TreeNode* root, int k){
|
||||
return findKthSmallest(root, &k)->val;
|
||||
}
|
Loading…
Reference in New Issue
Block a user