剑指_43_二叉搜索树第k大节点

本文介绍了一种通过中序遍历二叉搜索树来找到第K个节点的方法。利用二叉搜索树的特性,只需进行一次中序遍历,在遍历过程中计数即可高效地找到目标节点。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

因为二叉搜索树的中序遍历是有序,因此只要中序遍历到k次就可以了

/*
public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;

    public TreeNode(int val) {
        this.val = val;

    }

}
*/
public class Solution {
    int count=0;
    TreeNode KthNode(TreeNode pRoot, int k)
    {
        if(pRoot==null||k<=0) return null;
        TreeNode target=null;
        if(pRoot.left!=null) target=KthNode(pRoot.left,k);
        count++;
        if(target==null&&count==k){//如果遍历到这时,target仍然为空,且count=k那么target赋值为pRoot
			target=pRoot;
        }
        if(target==null&&pRoot.right!=null){//必须要此时target仍然为null,才进行遍历右子树,如果target不为空,那么不用遍历,直接返回即可。
            target=KthNode(pRoot.right,k);
        }
        return target;
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值