230. Kth Smallest Element in a BST
2016-06-26 21:38
302 查看
Given a binary search tree, write a function
smallest element in it.
Note:
You may assume k is always valid, 1 ≤ k ≤ BST's total elements.
Follow up:
What if the BST is modified (insert/delete operations) often and you need to find the kth smallest frequently? How would you 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).
直接中序遍历,第K个访问到的即是所求。
-----------------------------------------------------------------
O(height
of BST).的方法 https://leetcode.com/discuss/43771/implemented-java-binary-search-order-iterative-recursive
kthSmallestto find the kth
smallest element in it.
Note:
You may assume k is always valid, 1 ≤ k ≤ BST's total elements.
Follow up:
What if the BST is modified (insert/delete operations) often and you need to find the kth smallest frequently? How would you 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).
直接中序遍历,第K个访问到的即是所求。
int cnt; int ret=0; public int kthSmallest(TreeNode root, int k) { if(root!=null) inorder(root, k); return ret; } private void inorder(TreeNode t,int k) { if(t.left!=null) inorder(t.left, k); cnt++; if(cnt==k) { ret=t.val; return ; } if(t.right!=null) inorder(t.right, k); }
-----------------------------------------------------------------
O(height
of BST).的方法 https://leetcode.com/discuss/43771/implemented-java-binary-search-order-iterative-recursive
public int kthSmallest(TreeNode root, int k) { int count = countNodes(root.left); if (k <= count) { return kthSmallest(root.left, k); } else if (k > count + 1) { return kthSmallest(root.right, k-1-count); // 1 is counted as current node } return root.val; } public int countNodes(TreeNode n) { if (n == null) return 0; return 1 + countNodes(n.left) + countNodes(n.right); }