230. Kth Smallest Element in a BST(Java)
2017-08-14 22:06
134 查看
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?
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?
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public int kthSmallest(TreeNode root, int k) { int count = countNodes(root.left); if (k <= count) { return kthSmallest(root.left, k); } else if (k > count + 1) { return kthSmallest(root.right, k - 1 - count); } return root.val; } private int countNodes(TreeNode node) { if (node == null) return 0; return 1 + countNodes(node.left) + countNodes(node.right); } }
相关文章推荐
- LeetCode-230. Kth Smallest Element in a BST (JAVA)二叉树第k小的数字
- leetcode-java-230. Kth Smallest Element in a BST
- leetcode oj java 230. Kth Smallest Element in a BST
- Java for LeetCode 230 Kth Smallest Element in a BST
- LeetCode 230. Kth Smallest Element in a BST
- 【leetcode】230. Kth Smallest Element in a BST
- LeetCode#230. Kth Smallest Element in a BST
- 230. Kth Smallest Element in a BST
- [leetcode]230. Kth Smallest Element in a BST
- leetcode 230. Kth Smallest Element in a BST
- (java) Kth Smallest Element in a BST
- Leetcode 230. Kth Smallest Element in a BST
- 【LeetCode】 230. Kth Smallest Element in a BST
- Leetcode 230. Kth Smallest Element in a BST
- LeetCode 230. Kth Smallest Element in a BST
- [leetcode] 230. Kth Smallest Element in a BST
- 230. Kth Smallest Element in a BST
- 230. Kth Smallest Element in a BST
- [LeetCode] 230. Kth Smallest Element in a BST 解题思路
- Binary Search:230. Kth Smallest Element in a BST