From 496e012c7010708a3fb98a278413191f5e940d67 Mon Sep 17 00:00:00 2001 From: Alexander Pantyukhin Date: Sat, 17 Dec 2022 06:24:33 +0400 Subject: [PATCH] feat: add Kth Smallest Element in a BST (#1157) Co-authored-by: David Leal --- leetcode/DIRECTORY.md | 1 + leetcode/src/230.c | 35 +++++++++++++++++++++++++++++++++++ 2 files changed, 36 insertions(+) create mode 100644 leetcode/src/230.c diff --git a/leetcode/DIRECTORY.md b/leetcode/DIRECTORY.md index f45ca7a6..f14cb5c2 100644 --- a/leetcode/DIRECTORY.md +++ b/leetcode/DIRECTORY.md @@ -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 | diff --git a/leetcode/src/230.c b/leetcode/src/230.c new file mode 100644 index 00000000..61fa0e77 --- /dev/null +++ b/leetcode/src/230.c @@ -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; +}