卖萌的弱渣

I am stupid, I am hungry.

Kth Smallest Element in a BST

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?

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

Solution

  • Java inorder递归,但是要引入两个global 变量
(Kth-Smallest-Element-in-BST.java) download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    // 必须要有两个global 变量
    int ret;
    int count;
    public int kthSmallest(TreeNode root, int k) {
        ret = 0;
        count = k;
        inorder(root);
        return ret;

    }
    public void inorder(TreeNode root){
        if(root.left!=null)
            inorder(root.left);
        count--;
        if(count==0){
            ret = root.val;
            return ;
        }
        if (root.right!=null)  inorder(root.right);

    }
}
  • Mantain a stack to record the left subtree of current node.
(Kth-Smallest-Element-in-A-BST.py) download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def kthSmallest(self, root, k):
        """
        :type root: TreeNode
        :type k: int
        :rtype: int
        """
        stack = []
        # push the most left nodes
        node = root
        while node:
            stack.append(node)
            node = node.left
        while stack and k>0:
            node = stack.pop()
            k = k-1
            # push the left subtree of the node.right
            rightChild = node.right
            while rightChild:
                stack.append(rightChild)
                rightChild = rightChild.left
        return node.val