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.
answer:
Study is preorder
But pay attention to prune
. 1 class Solution { 2 public : . 3 the TreeNode KthNode * (* PROOT the TreeNode, int K) . 4 { . 5 IF (PROOT == nullptr a) return nullptr a; . 6 inOrder (PROOT, K); . 7 return RES; . 8 } . 9 void inOrder ( * PROOT the TreeNode, const int K) 10 { . 11 IF (n-> == K || PROOT nullptr a) return ; // prune and boundary processing 12 is inOrder (pRoot-> left, K); 13 ++n; 14 if (n == k && res == nullptr) 15 { 16 res = pRoot; 17 return; 18 } 19 inOrder(pRoot->right, k); 20 } 21 private: 22 int n = 0; 23 TreeNode *res = nullptr; 24 };