Given A binary search tree, write a function to kthSmallest
find the k-th 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.
- What if you could modify the BST node ' s structure?
- The optimal runtime complexity is O (height of BST).
Thinking Analysis: The basic is to achieve the BST sequence traversal, BST sequence traversal to get an ordered array, you can easily know the K decimal, the following gives a recursive implementation, with the help of counter record the number of node currently traversed, when Counter==k can return. Of course, the stack can also be used to implement iterative solutions. follow up: Further optimizations, we can keep some additional information in the node: the size of the Zuozi. The size of the left subtree is maintained at the same time when the delete is inserted. When searching, you can compare the size of the left subtree and the sizes of K to find out if the node is on the left or right, and is accelerated by the method of division. The time Complexity is O (h). The following pseudo code excerpt from http://bookshadow.com/weblog/2015/07/02/leetcode-kth-smallest-element-bst/if the properties of the BST node TreeNode can be extended, then add an attribute leftcnt and record the number of nodes in the left subtree Remember the current node
Loop when node is not empty:
if k = = node.leftcnt + 1: Returns node
Otherwise, if k > node.leftcnt: Then k-= node.leftcnt + 1, make node = Node.right
Otherwise, node = Node.left
The time complexity of the above algorithm is O (the height of BST)
AC Code
/** * Definition for a binary tree node. * public class TreeNode {* int val, * TreeNode left, * TreeNode right; * TreeNode (int x) {val = x;} *} */public class Solution {public int res = 0; public int counter = 0; public int kthsmallest (TreeNode root, int k) { Inorderk (root, k); return res; } public void Inorderk (TreeNode root, int k) { if (root.left!=null) Inorderk (Root.left, k); counter++; if (counter = = k) { res = root.val; return; } if (root.right!=null) Inorderk (Root.right, k); }}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Leetcode Kth Smallest Element in a BST