二叉搜索树的第k个结点(Java实现)

本文介绍了一种寻找二叉搜索树中第K大的结点的方法,通过中序遍历实现,最终返回所需的结点。适用于面试备考。

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

本题为剑指offer面试题63

牛客网测试地址:https://www.nowcoder.com/questionTerminal/ef068f602dde4d28aab2b210e859150a

[编程题]二叉搜索树的第k个结点
  • 热度指数:40095  时间限制:1秒  空间限制:32768K
给定一颗二叉搜索树,请找出其中的第k大的结点。例如, 5 / \ 3 7 /\ /\ 24 6 8 中,按结点数值大小顺序第三个结点的值为4。

Java code:
package go.jacob.day613;

import java.util.Stack;

/*
 * 二叉树中序遍历的应用
 * 二叉搜索树的中序遍历:从小到大输出节点
 */
public class Demo1 {
	TreeNode KthNode(TreeNode pRoot, int k) {
		if (pRoot == null || k <= 0)
			return null;
		int index = 0;
		TreeNode kthNode = null;
		TreeNode node = pRoot;
		Stack<TreeNode> stack = new Stack<TreeNode>();
		while (node != null || !stack.isEmpty()) {
			if (node != null) {
				stack.push(node);
				node = node.left;
			} else {
				node = stack.pop();
				index++;
				//当遍历到第k个节点时,跳出循环
				if (index == k) {
					kthNode = node;
					break;
				}
				node = node.right;
			}
		}
		return kthNode;
	}
}

class TreeNode {
	int val = 0;
	TreeNode left = null;
	TreeNode right = null;

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

	}

}



### 如何用 Java 判断一个二叉搜索树是否为完全二叉搜索树 #### 完全二叉树定义 完全二叉树是一种特殊的二叉树,在这种树中除了最后一层外,其他每一层都被完全填充,并且所有的节点都尽可能靠左排列[^1]。 #### 二叉搜索树定义 二叉搜索树(BST),也称为有序二叉树或排序二叉树,是指一棵空树或者具有下列性质的二叉树:若它的左子树不为空,则左子树上所有结点的值均小于根结点的值;若其右子树不为空,则右子树上所有结点的值均大于根结点的值;其左右子树也分别为二叉搜索树[^2]。 为了验证给定的一棵二叉搜索树是否也是完全二叉树,可以采用层次遍历的方法来检测。当遇到第一个叶子节点之后不应该再有非叶子节点出现。以下是具体的算法逻辑: - 使用队列来进行广度优先搜索。 - 遍历时记录首次遇见叶节点的位置。 - 如果在此位置之后还存在任何非叶节点则该树不是完全二叉树。 下面是完整的Java代码实现: ```java import java.util.LinkedList; import java.util.Queue; class TreeNode { int val; TreeNode left, right; public TreeNode(int item) { this.val = item; left = right = null; } } public class CompleteBinarySearchTreeChecker { private static boolean isCompleteBT(TreeNode root) { if (root == null) return true; // An empty tree is a complete binary tree Queue<TreeNode> queue = new LinkedList<>(); queue.add(root); boolean end = false; // Flag to mark the first leaf node encounter. while (!queue.isEmpty()) { TreeNode current = queue.poll(); if (current.left != null) { if (end) // If we have seen a leaf before and now see non-leaf return false; queue.offer(current.left); } else { end = true; // Mark that we've started seeing leaves } if (current.right != null) { if (end) // Same as above but for right child return false; queue.offer(current.right); } else { end = true; } } return true; } } ``` 此方法能够有效地检查给定的二叉搜索树是否满足完全二叉树的要求。需要注意的是这段代码假设输入已经是一颗有效的二叉搜索树
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值