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-02-08 22:04:02 发布