Share my c++ solution using a stack


  • 2
    Z

    We can easily associate it with the problem Binary Search Tree Iterator

    You can also view more solution on Github

    class Solution {
    public:
    	int kthSmallest(TreeNode* root, int k) {
    		stack<TreeNode*> s;
    		TreeNode* node = root;
    		while (node) {
    			s.push(node);
    			node = node->left;
    		}
    
    		int ans;
    		for (int i=0; i<k; i++) {
    			node = s.top();
    			s.pop();
    			ans = node->val;
    			node = node->right;
    			while (node) {
    				s.push(node);
    				node = node->left;
    			}
    		}
    		return ans;
    	}
    };

Log in to reply
 

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