博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
《剑指 Offer》——62、二叉搜索树的第k个结点
阅读量:2344 次
发布时间:2019-05-10

本文共 974 字,大约阅读时间需要 3 分钟。

1. 本题知识点

2. 题目描述

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

5 	  /   \ 	 3     7 	/ \   / \    2   4 6   8

3. 解题思路

对一棵二叉搜索树进行中序遍历,那么得到的遍历序列就是递增排序的。

4. 代码

public class TreeNode {
int val = 0; TreeNode left = null; TreeNode right = null; public TreeNode(int val) {
this.val = val; }}
public class Solution {
private int num; private TreeNode node; TreeNode KthNode(TreeNode pRoot, int k) {
// 特殊情况返回空 if (pRoot == null || k < 1) {
return null; } num = k; KthNode(pRoot); return node; } /** * 对二叉搜索树进行中序遍历,并找到第 k 小结点 * @param pRoot */ void KthNode(TreeNode pRoot) {
if (pRoot.left != null) {
KthNode(pRoot.left); } num--; if (num == 0) {
node = pRoot; return; } if (pRoot.right != null) {
KthNode(pRoot.right); } }}

转载地址:http://eyjvb.baihongyu.com/

你可能感兴趣的文章
love2d 苹果运行
查看>>
GridBagLayout 的注意
查看>>
ajax 跨域iis6 设置
查看>>
4.0版本改动
查看>>
IE8 9 ajax no-transport ajax 问题
查看>>
oracle 启动dbconsole
查看>>
entity-framework 6解决方案中多个项目使用
查看>>
ios基础
查看>>
unity3d
查看>>
metronic 1.5
查看>>
unity3d 4 assert store
查看>>
tab bar control 注意事项
查看>>
sql优化部分总结
查看>>
IDEA运行时动态加载页面
查看>>
UML总结(对九种图的认识和如何使用Rational Rose 画图)
查看>>
js遍历输出map
查看>>
easeui分页
查看>>
20个非常有用的Java程序片段
查看>>
Enterprise Architect使用教程
查看>>
Enterprise Architect 生成项目类图
查看>>