Offer surface prove safety questions. K-th node of the binary search tree

Title Description

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.
 
 
solution:

Since the binary search tree in order traversal is ascending, so that the counter can be added in order basis.

 1 class Solution {
 2 public:
 3     TreeNode* KthNode(TreeNode* pRoot, int k)
 4     {
 5         int i=INT32_MIN;
 6         return func(pRoot,k,i);
 7     }
 8     TreeNode* func(TreeNode* node,int k,int& i){
 9         if(node==nullptr){
10             if(i==INT32_MIN){
11                 i=0;
12             }
13             return nullptr;
14         }
15         decltype(node) t;
16         if(t=func(node->left,k,i)){
17             return t;
18         }
19         ++i;
20         if(i==k){
21             return node;
22         }
23         if(t=func(node->right,k,i)){
24             return t;
25         }
26         return nullptr;
27     }
28 };

 

Guess you like

Origin www.cnblogs.com/FdWzy/p/12306142.html