首页 > 其他 > 详细

Leetcode: Kth Smallest Element in a BST

时间:2015-12-19 13:43:28      阅读:245      评论: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?

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!