Kth Smallest Element in a BST
Total Accepted: 9992 Total Submissions: 33819My Submissions
Question Solution
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?
Method: According to the property of BST, the inOrder order is just the ascending order. So insert the BST as inOrder into an ArrayList then return list(k-1).
public class Solution { // the inOrder sequence is the ascending order. ArrayList<Integer> list = new ArrayList<Integer>(); public int kthSmallest(TreeNode root, int k) { insertArray(root); return list.get(k-1); } private void insertArray(TreeNode root) { if(root.left != null) insertArray(root.left); list.add(root.val); if(root.right != null) insertArray(root.right); } }
时间: 2024-10-20 10:36:47