The sword refers to offer: the kth node of the binary search tree

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.

ideas

The K-th inorder traversal of a binary search tree is

code

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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324758261&siteId=291194637