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

*Kth Smallest Element in a BST

时间:2015-08-31 06:26:51      阅读:202      评论:0      收藏:0      [点我收藏+]

标签:

题目:

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?

 

思路:

就是inorder traverse

 1     public int kthSmallest(TreeNode root, int k) 
 2     {
 3         
 4         ArrayList<Integer> re = new ArrayList<Integer>();
 5        // if(root==null)
 6     //        return re;
 7         helper(root,re);
 8         return re.get(k-1);
 9 
10     }
11     
12     public void helper(TreeNode root, ArrayList<Integer> re)
13     {
14         if(root==null)
15             return;
16         helper(root.left,re);
17         re.add(root.val);
18         helper(root.right,re);
19     }

reference:http://www.programcreek.com/2014/07/leetcode-kth-smallest-element-in-a-bst-java/

*Kth Smallest Element in a BST

标签:

原文地址:http://www.cnblogs.com/hygeia/p/4772083.html

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