LeetCode 230 -Kth Smallest Element in a BST ( JAVA )

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?

  1. The optimal runtime complexity is O(height of BST).

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    ArrayList al = new ArrayList();
    public int kthSmallest(TreeNode root, int k) {
        ListAll(root);
        return al.get(k-1);
    }
    
    public void ListAll(TreeNode root){
        if(root!=null){
            ListAll(root.left);
            al.add(root.val);
            ListAll(root.right);
        }
    }
}


LeetCode 230 -Kth Smallest Element in a BST ( JAVA )_第1张图片


总结,先插入把二叉排序树,中序遍历一遍,再插入链表中,全局的链表虽然这么用不是太好。。。

你可能感兴趣的:(LeetCode)