剑指Offer对答如流系列 - 二叉搜索树的第k个结点

面试题54:二叉搜索树的第k个结点

一、题目描述

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

例如,图中的二叉搜索树,按节点值大小顺序,第三大节点的值是4.
在这里插入图片描述
二叉搜索树的节点定义

	public class Node {
        int val = 0;
        Node left = null;
        Node right = null;

        public Node(int val) {
            this.val = val;
        }
    }

二、问题分析

二叉搜索树中序遍历的结果是顺序的。我们可以设置一个全局变量index,对二叉搜索树进行中序遍历时,每遍历一个结点,index++,当index=k时,该结点即为所求结点。

三、问题解答

	private int index=0;

    Node KthNode(Node pRoot, int k){
        Node pNode = null;
        if(pRoot==null || k<=0) {
            return pNode;
        }
        pNode = getKthNode(pRoot,k);
        return pNode;
    }

    private Node getKthNode(Node pRoot, int k){
        Node kthNode=null;

        if(pRoot.left!=null) {
            kthNode=getKthNode(pRoot.left,k);
        }
        
        if(kthNode==null){
            index++;
            if(k==index) {
                kthNode = pRoot;
            }
        }

        if(kthNode==null && pRoot.right!=null) {
            kthNode=getKthNode(pRoot.right,k);
        }
        
        return kthNode;
    }
  • 4
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值