二叉搜索树的第k个结点

题目描述:

给定一棵二叉搜索树,请找出其中的第k小的结点。例如, (5,3,7,2,4,6,8)    中,按结点数值大小顺序第三小结点的值为4。

/*
struct TreeNode {
    int val;
    struct TreeNode *left;
    struct TreeNode *right;
    TreeNode(int x) :
            val(x), left(NULL), right(NULL) {
    }
};
*/
class Solution {
public:
    int index = 0;
    TreeNode* KthNode(TreeNode* pRoot, int k)
    { 
        if(pRoot != NULL)
        {
            TreeNode* node = KthNode(pRoot->left,k);
                if(node != NULL)
                    return node;
            index++;  
            if(index == k)
                return pRoot;
            node = KthNode(pRoot->right,k);
            if(node != NULL)
                return node;
        }
        return NULL;
    }
    
};

 

全部评论

相关推荐

码农索隆:力扣的题目还挺贴近现实
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
07-08 13:05
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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