LeetCode OJ 230. Kth Smallest Element in a BST

Total Accepted: 46445 Total Submissions: 122594 Difficulty: Medium

 

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).

Credits:
Special thanks to @ts for adding this problem and creating all test cases.

二叉搜索树特点是对于任意一个节点,它的左子树的节点值都比它小,它的右子树的值都比它大。因此可以从树的最左边向上递归,同时计数,直到计数达到当前指定数字。
 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     private int cnt = 0;
12     public int kthSmallest(TreeNode root, int k) {
13         int result = 0;
14         if(root != null){
15             result = kthSmallest(root.left,k);
16             cnt++;
17             if(cnt == k){
18                 return root.val;
19             }
20             result += kthSmallest(root.right,k);
21         }
22         return result;
23     }
24 }

 

posted @ 2016-05-09 20:17  Black_Knight  阅读(130)  评论(0编辑  收藏  举报