feat: add Kth Smallest Element in a BST (#1157)

Co-authored-by: David Leal <halfpacho@gmail.com>
This commit is contained in:
Alexander Pantyukhin 2022-12-17 06:24:33 +04:00 committed by GitHub
parent bf94aff668
commit 496e012c70
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 36 additions and 0 deletions

View File

@ -61,6 +61,7 @@
| 217 | [Contains Duplicate](https://leetcode.com/problems/contains-duplicate/) | [C](./src/217.c) | Easy | | 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 | | 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 | | 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 | | 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 | | 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 | | 242 | [Valid Anagram](https://leetcode.com/problems/valid-anagram/) | [C](./src/242.c) | Easy |

35
leetcode/src/230.c Normal file
View 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;
}