C++ implementation using in-order BST traversal : I am a big fan of using C++ vectors


  • 0
    T
    /**
     * Definition for a binary tree node.
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution {
    // Do inorder traversal 
    private:
        TreeNode *node;
        vector<TreeNode*> leftMostNodes;
        
        void initialize(TreeNode* root)
        {
            node = root;
        }
        
        bool hasNext()
        {
            while(node)
            {
                leftMostNodes.push_back(node);
                node = node->left;
            }
            
            if(leftMostNodes.size() == 0)
                return false;
            else
                return true;
        }
        
        int next()
        {
            int value;
            node = leftMostNodes.back();
            value = node->val;
            leftMostNodes.pop_back();
            node = node->right;
            return value;
        }
    public:
        int kthSmallest(TreeNode* root, int k) {
            int value;
            int i;
            i = 0;
            initialize(root);
            while(hasNext())
            {
                i = i+1;
                value = next();
                if(i==k)
                    break;
            }
            return value;
        }
    };

Log in to reply
 

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