Given A binary search tree, write a function to kthSmallest
find the kth smallest element in it.
Note:
You may assume k are always valid, 1≤k≤bst's total elements.
Follow up:
What if the BST are modified (Insert/delete operations) often and you need to find the kth smallest frequently? How would optimize the Kthsmallest routine?
Hint:try to utilize the property of a BST.
This question is similar to the previous next () method, but there is one more K value here.
Questions and hints we need to use BTS's definition to follow the sequence: Left < root < right
So at the very beginning we first add all the rightmost TreeNode, not just the right thing, the node on the left is equally important.
Example: Stack.pop () after the present minimum value (only store the left TreeNode case), then pop () must be the second small? Certainly not, if the minimum node node.right!=null, it is clear that the value of node.right is smaller than the second-to-last node. (It's a little confusing, but it's a drawing comprehension.) =
So we then pop () out of the current minimum value, before the second pop () should immediately detect its node.right and put these values in the order store into the stack, and then the second run with the help of if statement.
The code is as follows. ~
public class Solution {public int kthsmallest (TreeNode root, int k) { stack<treenode> Stack = new stack< Treenode> (); TreeNode p = root; int result = 0; while (!stack.isempty () | | p!=null) { if (p!=null) { stack.push (p); p = p.left; } else{ TreeNode temp = Stack.pop (); k--; if (k==0) { result = Temp.val; } p = temp.right; } } return result;}}
[Leetcode] Kth smallest Element in a BST