Kth Smallest Element in a BST - Codeprg

Breaking

programing News Travel Computer Engineering Science Blogging Earning

Thursday, 13 August 2020

Kth Smallest Element in a BST

 

Kth Smallest Element in a BST

Kth Smallest Element in a BST

 

/**
 * 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) {}
 * };
 
 */
class Solution {
    private:
    vector<int> v;
public:
    void inorder(TreeNode* root)
    {
        if(root==NULL)return ;
        inorder(root->left);
        v.push_back(root->val);
        inorder(root->right);
    }
    int kthSmallest(TreeNode* root, int k) {
        inorder(root);
        return v[k-1];
       
    }
};

-----------------------------------------------------------------------------------------------------------------------------------

class Solution {
public:
   
    int kthSmallest(TreeNode* root, int k) {
        stack<TreeNode*> st;
        while(true)
        {
            while(root)
            {
                st.push(root);
                root = root->left;
            }
            root = st.top();
            st.pop();
            if(--k == 0) break;
            root = root->right;
        }
        return root->val;
       
    }
};