This link suggests a concise C + + recursive solution. The original code may is hard-understand at first and I have rewritten the code below. Need to run some examples and it to see how it works.
1 classSolution {2 Public:3 intKthsmallest (treenode* root,intk) {4 returnsmallest (root, k);5 }6 Private:7 intSmallest (treenode* node,int&k) {8 if(!node)return-1;9 intval = Smallest (node-Left , k);Ten if(!k)returnVal; One if(!--k)returnNode-Val; A returnSmallest (node-Right , k); - } -};
The same author also posts three solutions which is more space-efficient in this link. All of them reduce the o (n) space of the above code to O (k) space by using some nice data structures.
Personally I really love the soltuion using deque and I had rewritten it below.
1 classSolution {2 Public:3 intKthsmallest (treenode* root,intk) {4treenode* node =Root;5Deque<treenode*>nodes;6 while(true) {7 while(node) {8 Nodes.push_front (node);9 if(Nodes.size () >k)Ten Nodes.pop_back (); Onenode = nodeLeft ; A } -node =Nodes.front (); - Nodes.pop_front (); the if(!--k)returnNode-Val; -node = nodeRight ; - } - } +};
[Leetcode] Kth smallest Element in a BST