public class E54KthBSTNode {
//二叉搜索树中第k个节点
private static int index;
public static BinaryTreeNode getKthNode(BinaryTreeNode root, int k){
if (root == null)
return null;
index = k;
return getKthNodeCore(root);
}
private static BinaryTreeNode getKthNodeCore(BinaryTreeNode root) {
//采用二叉树的中序遍历顺序查找第k个节点
BinaryTreeNode target = null;
if (root.left != null)
target = getKthNodeCore(root.left);
if (target == null){
if (index == 1)
target = root;
index--;
}
if (target == null && root.right != null)
target = getKthNodeCore(root.right);
return target;
}
}
二叉搜索树的第K大节点(Java实现)
最新推荐文章于 2022-04-07 13:52:14 发布
本文介绍了一种在二叉搜索树中通过中序遍历找到第K个节点的算法实现。该算法首先初始化一个计数器,然后进行中序遍历,当计数器减至1时,当前节点即为所求的第K个节点。
&spm=1001.2101.3001.5002&articleId=102690169&d=1&t=3&u=ece0a8106757468ca1d18ca7695efeb3)
437

被折叠的 条评论
为什么被折叠?



