标签:
题目:
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:
链接: 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