230. Kth Smallest Element in a BST

来源:互联网 发布:phantom无人机控制软件 编辑:程序博客网 时间:2024/05/20 07:53

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?

/** * Definition for a binary tree node. * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */class Solution {    public int kthSmallest(TreeNode root, int k) {        List<Integer> res = new ArrayList<>();        inOrder(res, root, k);        return res.size() >= k ? res.get(k - 1) : 0;    }    private void inOrder(List<Integer> res, TreeNode root, int k) {        if (root == null || res.size() >= k)  return;        inOrder(res, root.left, k);        res.add(root.val);        inOrder(res, root.right, k);    }}