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

剑指offer算法题


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

题目分析
由于给定的是一颗二叉搜索树,而对于二叉搜索树来说,其中序遍历的结果就是该树升序排序后的结果。所以我们可以对该树进行中序遍历,然后找到第k个即可。

方法一 递归
下面是Java代码

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

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

    }

}
*/
public class Solution {
	//设置两个全局变量,一个用于计数,一个用于存储找到的节点。
    private int i =0;
    private TreeNode node = null;
    TreeNode KthNode(TreeNode pRoot, int k)
    {
        if(pRoot == null){
            return null;
        }
        if(k <=0){
            return null;
        }
        
        KthNode(pRoot.left,k);
        i++;
        if(i == k){
            node = pRoot;
        }
        KthNode(pRoot.right,k);
        
        return node;
    }
}

方法二 非递归

下面是Java代码

/*
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){
            return null;
        }
        if(k <=0){
            return null;
        }
        
        Stack<TreeNode> s = new Stack<>();
        int count = 0;
        while(!s.isEmpty()||pRoot!=null){
            if(pRoot!=null){
                s.push(pRoot); //直接压栈
                pRoot = pRoot.left;
            }else{
                TreeNode node = s.pop(); //出栈并访问
                if(++count == k){
                    return node;
                }
                pRoot = node.right;
            }
            
        }
        
        return null;
    }
}

参考https://www.nowcoder.com/practice/ef068f602dde4d28aab2b210e859150a?tpId=13&&tqId=11215&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值