#数据结构与算法学习笔记#剑指Offer60:二叉搜索树的第K个结点(Java、C/C++)

本文介绍了一种在二叉搜索树中寻找第K小结点的方法,通过中序遍历的方式,利用其排序特性,有效地找到目标结点。提供了Java和C++的实现代码。

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

2019.3.1     《剑指Offer》从零单刷个人笔记整理(66题全)目录传送门​​​​​​​

这题可以简单在纸上画一下,可以发现二叉搜索树的元素排序顺序,就是其中序遍历顺序。那就很简单了,中序遍历走一遍走到第K个结点返回即可。


题目描述

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


Java实现:

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



public class KthNode_61 {
	
	public static class TreeNode {
	    int val = 0;
	    TreeNode left = null;
	    TreeNode right = null;

	    public TreeNode(int val) {
	        this.val = val;
	    }
	}
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub

	}

	private static int num;
	private static TreeNode result;
	
	public static TreeNode KthNode(TreeNode pRoot, int k)
    {
        num = 0;
        result = null;
        Solution(pRoot, k);
        
        return result;
    }
	
	public static void Solution(TreeNode pRoot, int k) {
		if(pRoot == null || num == k) {
			return;
		}
		Solution(pRoot.left, k);
		num++;
		if(num == k) {
			result = pRoot;
			return;
		}
		Solution(pRoot.right, k);
	}
}

C++实现示例:

/*
struct TreeNode {
    int val;
    struct TreeNode *left;
    struct TreeNode *right;
    TreeNode(int x) :
            val(x), left(NULL), right(NULL) {
    }
};
*/
class Solution {
public:
    void inorder(TreeNode* root,TreeNode* &ans){
        if(root){
            inorder(root->left,ans);
            count--;
            if(!count) ans = root;
            inorder(root->right,ans);
        }
    }
    TreeNode* KthNode(TreeNode* pRoot, int k)
    {
        if(!pRoot || k < 1) return nullptr;
        TreeNode* ans = NULL;
        count = k;
        inorder(pRoot,ans);
        return ans;
    }
private:
    int count;
     
};

#Coding一小时,Copying一秒钟。留个言点个赞呗,谢谢你#

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值