Kth Smallest Element in a BST

class Solution {
public:
    int kthSmallest(TreeNode* root, int k) {
        int num = 0;
        TreeNode*pNode=NULL;
        visit(root, k, num, pNode);

        return pNode->val;
    }
    
private:
    void visit(TreeNode *root, int k, int &num, TreeNode*&pNode)
    {
        if (root == NULL)
        {
            return;
        }

        visit(root->left, k, num, pNode);
        
            
            if (++num == k)
            {
                pNode=root;
                return;
            }
        
        visit(root->right, k, num, pNode);
    }
};

此类方法遍历的时候,不要用返回值表示,如果有返回值,那么我们遍历到NULL时候,我们需要回退。此时如果带返回值,那么导致结果错误。

(只能使用不带返回值的void,这样我们才能回到上一层,且能继续执行下面的代码,否则我们将直接终止程序)

posted @ 2015-07-14 13:09  kkshaq  阅读(187)  评论(0编辑  收藏  举报