1. 程式人生 > >leetcode 230. Kth Smallest Element in a BST

leetcode 230. Kth Smallest Element in a BST

pan class http malle 就會 blog 返回值 替代 如果

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.

leetcode 230. Kth Smallest Element in a BST