Ninja technique🥷 to ACE DSA Interviews.
class Solution {
private:
void inorder(TreeNode* root, vector<int>& list)
{
if (!root) return;
inorder(root->left, list);
list.push_back(root->val);
inorder(root->right, list);
}
public:
int kthSmallest(TreeNode* root, int k)
{
vector<int> list;
inorder(root, list);
return list[k - 1];
}
};
class Solution {
private:
int ans = 0;
void inorder(TreeNode* root, int& k)
{
if (!root) return;
inorder(root->left, k);
k--;
if (k == 0) {
ans = root->val;
return;
}
inorder(root->right, k);
}
public:
int kthSmallest(TreeNode* root, int k)
{
inorder(root, k);
return ans;
}
};
class Solution {
public:
int kthSmallest(TreeNode* root, int k)
{
stack<TreeNode*> st;
while (1) {
while (root != NULL) {
st.push(root);
root = root->left;
}
root = st.top(), st.pop();
k--;
if (k == 0)
return root->val;
root = root->right;
}
return 0;
}
};