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

230. Kth Smallest Element in a BST

时间:2015-11-27 00:42:42      阅读:171      评论: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:

    1. Try to utilize the property of a BST.
    2. What if you could modify the BST node‘s structure?
    3. The optimal runtime complexity is O(height of BST).

链接:  http://leetcode.com/problems/kth-smallest-element-in-a-bst/

题解:

用了比较笨的方法 - inorder traversal,做了一下剪枝。

Time Complexity - O(k), Space Complexity - O(k)。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    List<Integer> nodeVal = new ArrayList<Integer>();
    
    public int kthSmallest(TreeNode root, int k) {
        if(root == null)
            return 0;
        inorder(root, k);
        return nodeVal.get(k - 1);
    }
    
    private void inorder(TreeNode root, int k) {
        if(nodeVal.size() >= k)
            return;
        if(root == null)
            return;
        inorder(root.left, k);
        nodeVal.add(root.val);
        inorder(root.right, k);
        
    }
}

 

Update:

Time Complexity - O(n), Space Complexity - O(1)

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    
    private int count = 0;
    private int res = 0;
    public int kthSmallest(TreeNode root, int k) {
        if(root == null)
            return 0;
        inorder(root, k);
        return res;
    }
    
    private void inorder(TreeNode root, int k) {
        if(root == null)
            return;
        if(count >= k)
            return;
        inorder(root.left, k); 
        if(count >= k)
            return;
        res = root.val;
        count++;
        inorder(root.right, k);
        
    }
}

 

Reference:

https://leetcode.com/discuss/43267/4-lines-in-c

https://leetcode.com/discuss/43464/what-if-you-could-modify-the-bst-nodes-structure

https://leetcode.com/discuss/43299/o-k-space-o-n-time-10-short-lines-3-solutions

https://leetcode.com/discuss/45684/share-my-c-iterative-alg

https://leetcode.com/discuss/43771/implemented-java-binary-search-order-iterative-recursive

 

230. Kth Smallest Element in a BST

标签:

原文地址:http://www.cnblogs.com/yrbbest/p/4999289.html

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