Offer wins the k-th node of the binary search tree;

1. Topic

Given a binary search tree, please find the first k smaller nodes therein. For example, (5,3,7,2,4,6,8), the numerical values ​​according to the third junction point is 4 summary.

Source: prove safety offer
links: https://www.nowcoder.com/practice/ef068f602dde4d28aab2b210e859150a?tpId=13&tqId=11215&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking

2. My problem solution

2.1 preorder

  • Binary search tree in order to traverse the array is in ascending order (tree node value); it is the first traversal sequence knumber is the first ksmall numbers;
/*
struct TreeNode {
    int val;
    struct TreeNode *left;
    struct TreeNode *right;
    TreeNode(int x) :
            val(x), left(NULL), right(NULL) {
    }
};
*/
class Solution {
    int cnt=0;
    TreeNode * res=NULL;
    void inOrder(TreeNode *root,int k){
        if(!root)return;
        inOrder(root->left,k);
        if(++cnt == k){
            res=root;
            return;
        }
        inOrder(root->right,k);
    }
public:
    TreeNode* KthNode(TreeNode* pRoot, int k)
    {
        cnt=0;
        inOrder(pRoot,k);
        return res;
    }

    
};

3. someone else's problem solution

4. Summary and Reflection

Published 70 original articles · won praise 0 · Views 2123

Guess you like

Origin blog.csdn.net/weixin_43951240/article/details/104209829