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.
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?
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).
/** * 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) { if (root == null) { return 0; } StackSolution2: recursivestack = new Stack (); int res = 0; while (!stack.isEmpty() || root != null) { if (root != null) { stack.push(root); root = root.left; } else { TreeNode temp = stack.pop(); k--; if (k == 0) { res = temp.val; } root = temp.right; } } return res; } }
Count the number of nodes of left subtree and right subtree recursively.
If the kth smallest element is in the right subtree, update k as k - (leftCount + 1) (leftCount + 1 = number of left subtree+root node). When k = leftCount + 1, we find the kth smallest element.
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public static int ans = 0; public int kthSmallest(TreeNode root, int k) { helper(root, k); return ans; } public int helper(TreeNode root, int k) { if (root == null) { return 0; } int leftCount = helper(root.left, k); int rightCount = helper(root.right, k - leftCount - 1); if (k == leftCount + 1) { ans = root.val; } return leftCount + 1 + rightCount; } }Reference: https://leetcode.com/discuss/54316/simple-and-clean-java-solution-with-explanation
Follow up:
Modify the structure of TreeNode, add int leftCount (number of nodes in left subtree of this node)
Assume current TreeNode is node, while (node != null) { if (k == node.leftCount + 1), return node.val; if (k > node.leftCount) { k -= node.leftCount + 1; node = node.right; } else { node = node.left; } }Reference: http://bookshadow.com/weblog/2015/07/02/leetcode-kth-smallest-element-bst/
No comments:
Post a Comment