[CareerCup][Google Interview] Find kth number in a BST
Find kth number in a BST
递归实现,按照左根右的顺序来实现
1 #include <iostream> 2 using namespace std; 3 4 struct Node 5 { 6 Node *left; 7 Node *right; 8 int val; 9 Node():left(NULL), right(NULL){} 10 }; 11 12 Node *findKthElement(Node *node, int &K) 13 { 14 if (node == NULL) 15 return NULL; 16 17 Node *left = findKthElement(node->left, K); 18 19 if (left != NULL) 20 return left; 21 22 K--; 23 24 if (K == 0) 25 return node; 26 27 Node *right = findKthElement(node->right, K); 28 29 return right; 30 } 31 32 int main() 33 { 34 Node node[10]; 35 36 for(int i = 0; i < 10; i++) 37 node[i].val = i; 38 39 node[4].left = &node[2]; 40 node[4].right = &node[7]; 41 42 node[2].left = &node[1]; 43 node[2].right = &node[3]; 44 45 node[1].left = &node[0]; 46 47 node[7].left = &node[6]; 48 node[7].right = &node[8]; 49 50 node[6].left = &node[5]; 51 52 node[8].right = &node[9]; 53 54 for(int i = 1; i <= 10; i++) 55 { 56 int k = i; 57 Node *ret = findKthElement(&node[4], k); 58 cout << i << "th element:" << ret->val << endl; 59 } 60 }