剑指 Offer 54. 二叉搜索树的第k大节点

本文介绍了一种寻找二叉搜索树中第K大节点的方法。提供了两种递归解法:一种使用中序遍历将节点值存入列表再返回目标值;另一种通过倒序中序遍历直接找到目标节点而无需额外空间。

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

思路:中序遍历

递归解法:

class Solution {
    public int kthLargest(TreeNode root, int k) {
        List<Integer> res=new ArrayList<Integer>();
        inorder(root,res);
        return res.get(res.size()-k);
    }
    public void inorder(TreeNode root, List<Integer> res){
        if(root==null)
            return;
        inorder(root.left,res);
        res.add(root.val);
        inorder(root.right,res);
    }
}

不需要额外空间,倒着中序遍历:

class Solution {
    int k,res;
    public int kthLargest(TreeNode root, int k) {
        this.k=k;
        res=0;
        inorder(root);
        return res;
    }
    public void inorder(TreeNode root){
        if(root==null)
            return;
        inorder(root.right);
        k--;
        if(k==0){
            res=root.val;
            return;
        }
        inorder(root.left);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值