Skip to content

Instantly share code, notes, and snippets.

@Gowtham-369
Last active May 20, 2020 12:58
Show Gist options
  • Save Gowtham-369/daaae66ecce91e31534b2ad1dec454b7 to your computer and use it in GitHub Desktop.
Save Gowtham-369/daaae66ecce91e31534b2ad1dec454b7 to your computer and use it in GitHub Desktop.
Day 19:LeetCode 30 Day may challenges
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
///// METHOD-1 /////
// best in space complexity
class Solution {
public:
// 5
// / \
// 4 7
//
//
int l = 0;
int ans;
void Inorder(TreeNode* root,int& k){
if(root == NULL)
return;
Inorder(root->left,k);
//cout<<root->val;
l+=1;
if(l == k)
ans = root->val;
Inorder(root->right,k);
}
int kthSmallest(TreeNode* root, int k) {
//my first idea is inorder traversal
Inorder(root,k);
return ans;
}
};
////// METHOD-2 //////
class Solution {
public:
// 5
// / \
// 4 7
//
//
vector<int> v;
void Inorder(TreeNode* root){
if(root == NULL)
return;
Inorder(root->left);
//cout<<root->val;
v.push_back(root->val);
Inorder(root->right);
}
int kthSmallest(TreeNode* root, int k) {
//my first idea is inorder traversal
Inorder(root);
return v[k-1];
}
};
Given a binary search tree, write a function kthSmallest to find the kth smallest element in it.
Note:
You may assume k is always valid, 1 ≤ k ≤ BST's total elements.
Example 1:
Input: root = [3,1,4,null,2], k = 1
3
/ \
1 4
\
2
Output: 1
Example 2:
Input: root = [5,3,6,2,4,null,null,1], k = 3
5
/ \
3 6
/ \
2 4
/
1
Output: 3
Follow up:
What if the BST is modified (insert/delete operations) often and you need to find the kth smallest frequently? How would you optimize the kthSmallest routine?
Hide Hint #1
Try to utilize the property of a BST.
Hide Hint #2
Try in-order traversal. (Credits to @chan13)
Hide Hint #3
What if you could modify the BST node's structure?
Hide Hint #4
The optimal runtime complexity is O(height of BST).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment