[LeetCode]Kth Smallest Element in a BST
发布日期:2021-11-22 02:48:59 浏览次数:3 分类:技术文章

本文共 731 字,大约阅读时间需要 2 分钟。

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);	}}

转载地址:https://blog.csdn.net/zxdfc/article/details/48765401 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:SpringMVC中的自定义视图使用BeanNameViewResolver出现了不能使用的错误解决
下一篇:[LeetCode]Combinations

发表评论

最新留言

初次前来,多多关照!
[***.217.46.12]2024年04月01日 10时38分29秒