标签:
Given a binary search tree, write a function kthSmallest to 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).
Java Solution 1 - Inorder Traversal
We can inorder traverse the tree and get the kth smallest element. Time is O(n).
1 /** 2 * Definition for a binary tree node. 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode(int x) { val = x; } 8 * } 9 */ 10 public class Solution { 11 public int kthSmallest(TreeNode root, int k) { 12 TreeNode node = root; 13 Stack<TreeNode> st = new Stack<TreeNode>(); 14 int counter = 0; 15 while (!st.isEmpty() || node != null) { 16 if (node != null) { 17 st.push(node); 18 node = node.left; 19 } 20 else { 21 node = st.pop(); 22 counter++; 23 if (counter == k) return node.val; 24 node = node.right; 25 } 26 } 27 return -1; 28 } 29 }
Java Solution 2 - Extra Data Structure
We can let each node track the order, i.e., the number of elements that are less than itself(left Subtree size). Time is O(log(n)).
Leetcode: Kth Smallest Element in a BST
标签:
原文地址:http://www.cnblogs.com/EdwardLiu/p/5058978.html