求二叉搜索树的第k小节点

求二叉搜索树的第k小节点

一、思路

二叉搜索树按照中序遍历的顺序打印出来正好就是排序好的顺序, 第 k 个结点就是第 K 大的节点,分别递归查找左右子树的第 K 个节点, 或使用非递归借用栈的方式查找, 当 count=k 时返回根节点。

二、实现代码

代码实现(如下):

private int count = 0;
public TreeNode KthNode(TreeNode pRoot, int k) {
    
    
	if (pRoot == null) {
    
    
		return null;
	}
	TreeNode node = KthNode(pRoot.left, k); //向左子树递归
	if (node != null) {
    
    
		return node;
	}
	count++if (count == k) {
    
    
		return pRoot;
	}
	node = KthNode(pRoot.right, k); //向右子树递归
	return node;
}

猜你喜欢

转载自blog.csdn.net/weixin_43558210/article/details/113773905