|
| 1 | +--- |
| 2 | +id: kth smallest element in binary search tree |
| 3 | +title: Kth Smallest Element in Binary Search Tree |
| 4 | +sidebar_label: 0230 Kth Smallest Element in Binary Search Tree |
| 5 | +tags: |
| 6 | + - tree |
| 7 | + - tree traversal |
| 8 | + - LeetCode |
| 9 | + - C++ |
| 10 | +description: "This is a solution to theKth Smallest Element in Binary Search Tree problem on LeetCode." |
| 11 | +--- |
| 12 | + |
| 13 | +## Problem Description |
| 14 | + |
| 15 | +Given the root of a binary search tree, and an integer k, return the kth smallest value (1-indexed) of all the values of the nodes in the tree. |
| 16 | + |
| 17 | +### Examples |
| 18 | + |
| 19 | +**Example 1:** |
| 20 | + |
| 21 | +``` |
| 22 | +
|
| 23 | +Input: root = [3,1,4,null,2], k = 1 |
| 24 | +Output: 1 |
| 25 | +``` |
| 26 | + |
| 27 | +**Example 2:** |
| 28 | + |
| 29 | +``` |
| 30 | +Input: root = [5,3,6,2,4,null,null,1], k = 3 |
| 31 | +Output: 3 |
| 32 | +``` |
| 33 | + |
| 34 | +### Constraints |
| 35 | + |
| 36 | +- The number of nodes in the tree is n. |
| 37 | +- `1 <= k <= n <= 10^4` |
| 38 | +- `0 <= Node.val <= 10^4` |
| 39 | + |
| 40 | +### Approach |
| 41 | + |
| 42 | +To solve this problem(Kth smallest element in BST) we will do the inorder traversal of the tree as we know in a binary search tree the array of elements which we get after inorder traversal they will be in sorted order so the kth smallest element in the given BST will be the kth index(1-indexed) element in inorder traversal of the BST. |
| 43 | + |
| 44 | +#### Code in C++ |
| 45 | + |
| 46 | +```cpp |
| 47 | +/** |
| 48 | + * Definition for a binary tree node. |
| 49 | + * struct TreeNode { |
| 50 | + * int val; |
| 51 | + * TreeNode *left; |
| 52 | + * TreeNode *right; |
| 53 | + * TreeNode() : val(0), left(nullptr), right(nullptr) {} |
| 54 | + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} |
| 55 | + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} |
| 56 | + * }; |
| 57 | + */ |
| 58 | +class Solution { |
| 59 | +public: |
| 60 | + // Function for inorder traversal |
| 61 | + void inorder(TreeNode* root,vector<int>&a){ |
| 62 | + if(root==NULL){ |
| 63 | + return; |
| 64 | + } |
| 65 | + inorder(root->left,a); |
| 66 | + a.push_back(root->val); |
| 67 | + inorder(root->right,a); |
| 68 | + } |
| 69 | + // Function to get the kth smallest element |
| 70 | + int kthSmallest(TreeNode* root, int k) { |
| 71 | + vector<int>a; |
| 72 | + inorder(root,a); |
| 73 | + return a[k-1]; // as 0-indexed |
| 74 | + } |
| 75 | +}; |
| 76 | +``` |
| 77 | +
|
| 78 | +
|
0 commit comments