文章524
标签277
分类67

算法:二叉搜索树的第k个结点


二叉搜索树的第k个结点

二叉搜索树的第k个结点

给定一棵二叉搜索树,请找出其中的第k小的结点。

例如, (5,3,7,2,4,6,8) 中,按结点数值大小顺序第三小结点的值为4。


分析

对于二叉树的中序遍历即为有序数列;

所以设置一个index, 对二叉树进行中序遍历;

如果index==k则直接返回;


代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public class Solution {
int index = 0;

TreeNode KthNode(TreeNode root, int k) {
if (root != null) {
TreeNode node = KthNode(root.left, k);
if (node != null)
return node;
index++;
if (index == k)
return root;
node = KthNode(root.right, k);
if (node != null)
return node;
}
return null;
}
}

本文作者:Jasonkay
本文链接:https://jasonkayzk.github.io/cn/1996/07/27/%E7%AE%97%E6%B3%95-%E4%BA%8C%E5%8F%89%E6%90%9C%E7%B4%A2%E6%A0%91%E7%9A%84%E7%AC%ACk%E4%B8%AA%E7%BB%93%E7%82%B9/
版权声明:本文采用 CC BY-NC-SA 3.0 CN 协议进行许可