Thursday, August 13, 2015

[LeetCode] Kth Smallest Element in a BST

Given a binary search tree, write a function kthSmallest to find the kth smallest element in it.
Note: 
You may assume k is always valid, 1 ≤ k ≤ BST's total elements
Analysis: Note, in order traverse a BST will get a sorted array from smallest to biggest.
    int visit(TreeNode* root, int k, int &i){
        if(!root)   return 0;
        int res = visit(root->left,k,i);
        if(i == k)  return res;
        if(++i == k)    return root->val;
        return visit(root->right,k,i);
    }
    
    int kthSmallest(TreeNode* root, int k) {
        int i=0;
        return visit(root,k,i);
    }