Kth smallest Element in a BSTTotal Accepted:
3655 Total Submissions:
12149
Given A binary search tree, write a function to kthSmallest
find thek-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?
Ideas
Recursion and non-recursion can be used. Here I used a non-recursive approach, similar to binary tree iterator. By the way, I looked at the recursive method on the Internet, the time complexity is very high, each time to calculate the tree size. Feeling even recursion, should also be able to optimize.
follow up is interesting to keep some extra information in the node: the size of the Zuozi. It is also necessary to maintain the size of the left subtree while inserting deletes. When looking again, you can use two points. Time Complexity of O (h)
[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 kthsmallest (TreeNode root, int k) { stack<treenode> Stack = new stack& Lt;> (); TreeNode n = root; while (n.left!=null) { stack.push (n); n = n.left; } while (k>0 && (n!=null | |!stack.isempty ())) { if (n==null) { n = stack.pop (); if (--k==0) return n.val; n = n.right; } else { stack.push (n); n = n.left; } } return n.val;} }
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Leetcode 230:kth Smallest Element in a BST