码迷,mamicode.com
首页 > 其他好文 > 详细

8.3 LeetCode230 Return the kth smallest element of a BST

时间:2015-08-04 09:25:26      阅读:113      评论:0      收藏:0      [点我收藏+]

标签:

Kth Smallest Element in a BST

 Total Accepted: 9992 Total Submissions: 33819My Submissions

 

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);
    }
}

 

8.3 LeetCode230 Return the kth smallest element of a BST

标签:

原文地址:http://www.cnblogs.com/michael-du/p/4700953.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!