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
k
number is the firstk
small 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;
}
};