leetcode 230. Kth Smallest Element in a BST

https://www.cnblogs.com/grandyang/p/4620012.html

这个题其实就是中序遍历第k个数就好了,代码最好写的就是非递归的方式,在stack里面找第k个就好了。也可以使用递归的方式:

class Solution {
public:
    int kthSmallest(TreeNode* root, int k) {
        return Smallest(root,k);
    }
    int Smallest(TreeNode* root,int& k){
        if(root == NULL)
            return -1;
        int num = Smallest(root->left,k);
        if(k == 0)
            return num;
        if(--k == 0)
            return root->val;
        return Smallest(root->right,k);
    }
};

注意:这种递归的方法在NULL时候返回-1,如果找到了数字,返回值就会以当前的结果替代-1.

另一种写法:

自己写的

/**
 * 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 {
public:
    int kthSmallest(TreeNode* root, int k) {
        int index = 0,num = -1;
        kthSmallest(root,k,index,num);
        return num;
    }
    void kthSmallest(TreeNode* root,int k,int& index,int& num){
        if(!root)
            return;
        kthSmallest(root->left,k,index,num);
        index++;
        if(index == k){
            num = root->val;
            return;
        }
        kthSmallest(root->right,k,index,num);
    }
};
原文地址:https://www.cnblogs.com/ymjyqsx/p/10675805.html