Tuesday, October 31, 2017

230. Kth Smallest Element in a BST

https://leetcode.com/problems/kth-smallest-element-in-a-bst/description/
    int kthSmallest(TreeNode* root, int k) {
        int res;
        inOrder(root, k, res);
        return res;
    }
    void inOrder(TreeNode* node, int& k, int& res) {
        if(!node) return;
        if(k>0) inOrder(node->left, k, res);
        k--;
        if(k ==0) { res = node->val; return; }
        if(k>0) inOrder(node->right, k, res);
    }

No comments:

Post a Comment