K-th node AcWing 70. Binary search tree (the offer to prove safety)

Given a binary search tree, please find the first k smaller nodes therein.

You may assume that tree and k are present, and 1≤k≤ tree summary points.

Sample
input: root = [2, 1, 3, null, null, null, null], k = 3

2

/
1 3

Output: 3

class Solution {
public:
    TreeNode* ans;
    TreeNode* kthNode(TreeNode* root, int k) {
        if(!root) return root;
        dfs(root,k);
        return ans;
    }
    
    void dfs(TreeNode* root,int &k) {
        if(!root) return;
        dfs(root -> left,k);
        k--;
        if(!k) ans = root;
        dfs(root -> right,k);
    }
};
Published 843 original articles · won praise 28 · views 40000 +

Guess you like

Origin blog.csdn.net/tomjobs/article/details/104980596