902. Kth Smallest Element in a B

2019-06-07  本文已影响0人  鸭蛋蛋_8441

Description

Given a binary search tree, write a function kthSmallest to find the kth smallest element in it.

You may assume k is always valid, 1 ≤ k ≤ BST's total elements.

Example

Example 1:

Input:{1,#,2},2

Output:2

Explanation:

1

\

  2

The second smallest element is 2.

Example 2:

Input:{2,1,3},1

Output:1

Explanation:

  2

/ \

1  3

The first smallest element is 1.

Challenge

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?

思路:

总体就是中序遍历的第K个点即为答案, 有递归和非递归两种实现方法,递归又有用全局变量或者传参数两种方法。非递归的中序遍历要用到栈的概念,答案还用了个dummy node节省了对于根节点非空的判断。

代码:

递归的使用传参数的方法:

非递归的方法:

上一篇 下一篇

猜你喜欢

热点阅读