# 二叉搜索树的第k个节点|博客系列

> 本文详细讲解如何在二叉搜索树中查找第k小的节点，包含题目描述、解题思路和JavaScript代码实现，适合数据结构与算法学习者参考。

- 原文：https://feinterview.poetries.top/docs/fe-blog-docs/blog-docs/data-struct/12-%E4%BA%8C%E5%8F%89%E6%90%9C%E7%B4%A2%E6%A0%91%E7%9A%84%E7%AC%ACk%E4%B8%AA%E8%8A%82%E7%82%B9
- 来源：前端进阶之旅（feinterview.poetries.top）
- 更新：2025.10.25

---

## 二叉搜索树的第k个节点📕

### 题目描述

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

### 解题思路

1. 利用二叉搜索树**中序遍历**就是按从小到大的特性；
2. 中序遍历排好序后返回对应`k-1`下标的那一项节点。

### coding

```javascript
/*
* 二叉树结点类
*/
class Node {
    constructor(value = 0, left = null, right = null) {
        this.value = value;
        this.left = left;
        this.right = right;
    }
}
/**
* 二叉搜索树的第k个节点
* @param {Node} root
* @param {Number} target
 */
function KthNode(root, target) {
    const arr = []
    inOrderRec(root, arr)
    if (target > 0 && target <= arr.length) {
        return arr[target - 1]
    }
    return null;
}
/*
* 二叉树中序递归遍历
*/
function inOrderRec (node, arr) {
    if (node) {
        inOrderRec(node.left, arr)
        arr.push(node)
        inOrderRec(node.right, arr)
    }
}
/*
* 二叉树中序非递归遍历
*/
// function inOrderUnRec (node) {
//   let list = [];
//   let stack = [];
//   while (stack.length !== 0 || node) {
//     if (node) {
//       stack.push(node);
//       node = node.left;
//     } else {
//       node = stack.pop();
//       list.push(node);
//       node = node.right;
//     }
//   }
//   return list;
// }

const root = new Node(
  2,
  new Node(1),
  new Node(
    5,
    new Node(4),
    new Node(6)
  )
);
console.log(KthNode(root, 3))
// { value: 4, left: null, right: null }
```
