A non-recursive algorithm coded by C++


  • 0
    F
    int kthSmallest(TreeNode* root, int k) {
        int count=0;
        TreeNode* p = root;
        stack<TreeNode*> st;
        
        while(p!=NULL||!st.empty()){
            while(p!=NULL){
                st.push(p);
                p=p->left;
            }
            if(!st.empty()){
                p=st.top();
                st.pop();
                if(++count==k){
                    return p->val;
                }else{
                    p=p->right;
                }
            }
        }
        return -1;
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.