题解 | #二叉搜索树的第k个结点#

二叉搜索树的第k个结点

http://www.nowcoder.com/practice/ef068f602dde4d28aab2b210e859150a

/*
struct TreeNode {
    int val;
    struct TreeNode *left;
    struct TreeNode *right;
    TreeNode(int x) :
            val(x), left(NULL), right(NULL) {
    }
};
*/
class Solution {
public:
    int j = 0;
    TreeNode* temp;
    TreeNode* KthNode(TreeNode* pRoot, int k) {
        TreeNode* res = pRoot;
        if(!pRoot || k == 0)
            return nullptr;
        if(pRoot->left) {
            KthNode(pRoot->left, k);
        }
        j++;
        if(j == k) {
            temp = res;
        }
        if(pRoot->right) {
            KthNode(pRoot->right, k);
        }
        return j < k ? nullptr : temp; // 不能判定j==k,因为递归到j==k时不能停止,会持续到把所有节点遍历完
    }

    
};
全部评论

相关推荐

老板加个卤鸡蛋:HR看了以为来卧底来了
点赞 评论 收藏
分享
NBA球星伦纳德:jd是这样的,工作连拧螺丝都算不上
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务