首页 > 学院 > 开发设计 > 正文

二叉搜索树的第k个结点

2019-11-08 02:05:48
字体:
来源:转载
供稿:网友
题目描述

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

IDEA

二叉搜索树->左<根<右->中序遍历

CODE

/*struct TreeNode {    int val;    struct TreeNode *left;    struct TreeNode *right;    TreeNode(int x) :            val(x), left(NULL), right(NULL) {    }};*/class Solution {    int count=0;    TreeNode* resNode=NULL;public:    TreeNode* KthNode(TreeNode* PRoot, int k)    {        if(pRoot==NULL)            return NULL;        InOrder(pRoot,k);        return resNode;    }     void InOrder(TreeNode *pRoot,int k){        if(pRoot->left)            InOrder(pRoot->left,k);        if(++count==k)            resNode=pRoot;        if(pRoot->right)            InOrder(pRoot->right,k);    }};


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表