Cattle off - the k-th node binary search tree

Description Title
given a binary search tree, find the k-th smaller nodes therein. For example, (5,3,7,2,4,6,8), the numerical values according to the third junction point is 4 summary.
Solution: In order traversal, consider k <= 0 and where k is greater than the total number of nodes

class Solution {
    int cnt = 0;
    TreeNode * knode = NULL;
public:
    void DFS(TreeNode* pRoot, int k)
    {
        if (pRoot->left && cnt<k)
            DFS(pRoot->left, k);
        if (++cnt == k)
            knode = pRoot;
        if (pRoot->right && cnt<k)
            DFS(pRoot->right, k);
    }
    TreeNode* KthNode(TreeNode* pRoot, int k)
    {
        if (pRoot==NULL || k <= 0)
            return NULL;
        DFS(pRoot, k);
        return knode;
    }
};
Published 315 original articles · won praise 119 · views 110 000 +

Guess you like

Origin blog.csdn.net/w144215160044/article/details/104962619