Leetcode 230 Solution

This article provides solution to leetcode question 230 (kth-smallest-element-in-a-bst)

https://leetcode.com/problems/kth-smallest-element-in-a-bst

Solution

/**
 * 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 {
    int m_res;
public:
    void visit(TreeNode* node, int* pk)
    {
        if (node == NULL)
            return;

        if (*pk == 0)
            return;

        visit(node->left, pk);

        (*pk)--;

        if (*pk == 0)
        {
            m_res = node->val;
        }
        else
        {
            visit(node->right, pk);
        }
    }

    int kthSmallest(TreeNode* root, int k) {
        visit(root, &k);
        return m_res;
    }
};