【剑指Offer-Java】二叉搜索树的第k个结点

二叉搜索树的第k个结点

题目描述

给定一棵二叉搜索树,请找出其中的第k小的结点。例如, (5,3,7,2,4,6,8) 中,按结点数值大小顺序第三小结点的值为4。

思路

中序遍历二叉搜索树得到的就是有序序列,再找到第k个即可

实现

递归实现

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

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

    }

}
*/
public class Solution {
    int cnt=0;  //记录遍历元素的个数
    TreeNode KthNode(TreeNode pRoot, int k)
    {
        //中序遍历
        //递归出口
        if(pRoot==null || k<=0) return null;
        
        //当前遍历到的结点node
        
        //遍历左子树:递归:在左子树找到第k个了就返回第k个结点,否则就是null
        TreeNode node=KthNode(pRoot.left,k);
        //判断左子树是否满足k个,node不为null,说明找到第k个了
        if(node!=null){
            return node;
        }
        
        //若node为null,说明左子树没有k个,继续根结点
        cnt++;  //遍历完根结点,cnt+1
        if(cnt==k){  //个数正好为k:根就是第k个
            return pRoot;
        }
        
        //遍历完根也不够k,就继续右子树(类似左子树)
        node=KthNode(pRoot.right,k);
        if(node!=null){
            return node;
        }
        return null;   //遍历完整树都没找到第K个结点
    }
}

非递归(栈实现)

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

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

    }

}
*/
import java.util.Stack;
public class Solution {
    //使用栈实现非递归中序遍历
    TreeNode KthNode(TreeNode pRoot, int k)
    {
        if(pRoot==null || k==0) return null;
        int count=0;  //当前遍历结点数(计数器)
        Stack<TreeNode> stack=new Stack<>();
        while(pRoot!=null || !stack.isEmpty()){
            while(pRoot!=null){
                stack.push(pRoot);
                pRoot=pRoot.left;
            }
            pRoot=stack.pop();
            count++;
            //如果当前遍历结点数到达k,就输出该结点
            if(count==k){
                return pRoot;
            }
            //继续遍历右子树
            pRoot=pRoot.right;
        }
        return null;    //找不到第k个时
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值