## Topic description

Given a binary search tree, find the kth largest node in it. For example, in 5 / \ 3 7 /\ /\ 2 4 6 8, the value of the third node in the numerical order of the nodes is 4.

## Problem solving ideas

An important property of a binary search tree is that its in-order traversal is sorted, so this problem only needs to use the in-order traversal algorithm to traverse a binary search tree, and it is easy to find its Kth largest node.
Inorder traversal is easier to implement recursively, but what to do when traversing to a root node?
When printing a binary tree in inorder traversal, we print the root node after recursing the left subtree. Of course, this topic does not require printing. If the left child node is not the node to be found, the root node will be accessed, so the access to The operation to be done at the root node is to subtract 1 from K, because the left child node has been confirmed not to be the node to be found, and the left child node is excluded.
This process can be regarded as the process of target shifting. Every time a node is moved, K is reduced by 1, until K is equal to 1, the current node is the required node.

## Non-recursive version:

``````/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};
*/
class Solution {
int count = 0;
public:
TreeNode* KthNode(TreeNode* pRoot, int k)
{
if(pRoot == NULL || k == 0)
return NULL;
return KthNodeCore(pRoot, k);
}

TreeNode* KthNodeCore(TreeNode* pRoot, int& k){
TreeNode* target = NULL;
// 先成左子树中找
if(pRoot->left != NULL)
target = KthNodeCore(pRoot->left, k);
// 如果在左子树中没有找到
if(target == NULL){
//说明当前的根结点是所要找的结点
if(k == 1)
target = pRoot;
// 当前的根结点不是要找的结点，但是已经找过了，所以计数器减一
else
k--;
}
// 根结点以及根结点的左子树都没有找到，则找其右子树
if(target == NULL && pRoot->right != NULL)
target = KthNodeCore(pRoot->right, k);
return target;
}
};``````

## Recursive version:

``````/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};
*/
class Solution {
int count = 0;
public:
TreeNode* KthNode(TreeNode* pRoot, int k)
{
if(pRoot){
TreeNode *ret = KthNode(pRoot->left, k); //先成左子树中找
if(ret) return ret;  // 左子树中找到符合要求的节点返回
if(++count == k) return pRoot; //从最左节点开始，count+，当++count == k时说明当前的根结点是所要找的结点
ret = KthNode(pRoot->right,k); //根结点以及根结点的左子树都没有找到，则找其右子树
if(ret) return ret;
}
return nullptr;
}
};``````

### Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324625636&siteId=291194637
Recommended
Ranking
Daily