# 54.二叉搜索树的第k大节点

### 一、 题目

给定一棵二叉搜索树，请找出其中第 k 大的节点的值。

示例 1:

输入: root = \[3,1,4,null,2], k = 1

```
3
/ \
1   4
\
   2
```

输出: 4

示例 2:

输入: root = \[5,3,6,2,4,null,null,1], k = 3

```
 5
/ \
3   6
/ \
2   4
/
1
```

输出: 4   限制：

1 ≤ k ≤ 二叉搜索树元素个数

来源：力扣（LeetCode）

链接：<https://leetcode-cn.com/problems/er-cha-sou-suo-shu-de-di-kda-jie-dian-lcof>

著作权归领扣网络所有。商业转载请联系官方授权，非商业转载请注明出处。

### 二、 分析

根据二叉搜索树的特性，我们通过中序遍历得到有序的数组就可以轻松获得结果

```
func kthLargest(_ root: TreeNode?, _ k: Int) -> Int {
    var inorderArr: [Int] = []
    
    func inorder(_ node: TreeNode?) {
        guard let n = node else {
            return
        }
        
        inorder(n.right)
        inorderArr.append(n.val)
        inorder(n.left)
    }
    
    inorder(root)
    
    return inorderArr[k - 1]
}
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://ryukiedev.gitbook.io/wiki/shu-ju-jie-gou-yu-suan-fa/jian-zhi-offerswift/54.-er-cha-sou-suo-shu-de-dikda-jie-dian.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
