230. Kth Smallest Element in a BST

网友投稿 744 2022-09-04

230. Kth Smallest Element in a BST

230. 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?

/** * 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 res = new ArrayList<>(); inOrder(res, root, k); return res.size() >= k ? res.get(k - 1) : 0; } private void inOrder(List 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); }}

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:38个小技巧告诉你如何快速学习MySQL数据库(如何快速学会数据库)
下一篇:236. Lowest Common Ancestor of a Binary Tree
相关文章

 发表评论

暂时没有评论,来抢沙发吧~