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?
/*** Definition for a binary tree node. * public class TreeNode {* int val; * TreeNode left; * TreeNode rig Ht * TreeNode (int x) {val = x;} }*/ Public classSolution {Private intn = 0; PrivateTreeNode Re_node; //Middle sequence Traversal binary sort tree Public voidInordertravel (TreeNode root,intk) {if(root!=NULL) {inordertravel (root.left,k); N++; if(n==k) { This. Re_node =Root; return; } inordertravel (Root.right,k); } } Public intKthsmallest (TreeNode root,intk) {inordertravel (root,k); return This. Re_node.val; }}
Kth smallest Element in a BST