[LeetCode]Kth Smallest Element in a BST

来源:互联网 发布:写关于宿舍知乎 编辑:程序博客网 时间:2024/06/05 16:28

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?

题解:使用DFS,BTS的结构是root.left<root<root.right,采用中序遍历,可以得到k小的值。

code:

public class Solution {    private int value;private int index;public int kthSmallest(TreeNode root, int k) {index = 0;dfs(root, k);return value;}public void dfs(TreeNode root, int k) {if(root == null)return;dfs(root.left, k);index++;if (index == k) {value = root.val;return;}dfs(root.right, k);}}

0 0
原创粉丝点击