中序遍历二叉搜索树,遍历到第k个节点的时候保存改节点的值并退出程序。
/**
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param proot TreeNode类
* @param k int整型
* @return int整型
*/
int res = -1;
int flag = 1;
int KthNode(struct TreeNode* proot, int k ) {
// write code here
void f(struct TreeNode* proot, int k ,int count);
f(proot,k,0);
return res;
}
void f(struct TreeNode* proot, int k ,int count){
if(!flag) return;
if(!proot) return;
f(proot->left,k,count);
res = proot->val;
count++;
if(count==k){
flag = 0;
return;
}
f(proot->right,k,count);
}