From d9bef6466049ae22a2dff098a7bb6bf88cd1c0a9 Mon Sep 17 00:00:00 2001 From: Omooo <869759698@qq.com> Date: Sun, 19 Jul 2020 10:08:35 +0800 Subject: [PATCH] =?UTF-8?q?Update=20=E4=BA=8C=E5=8F=89=E6=A0=91=E7=9B=B8?= =?UTF-8?q?=E5=85=B3.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Algorithm/剑指 Offer/二叉树相关.md | 44 +++++++++++++++++++ 1 file changed, 44 insertions(+) diff --git a/blogs/Algorithm/剑指 Offer/二叉树相关.md b/blogs/Algorithm/剑指 Offer/二叉树相关.md index a46d742..e38fc0d 100644 --- a/blogs/Algorithm/剑指 Offer/二叉树相关.md +++ b/blogs/Algorithm/剑指 Offer/二叉树相关.md @@ -510,3 +510,47 @@ class Solution { } ``` +#### [Offer 54. 二叉搜索树的第k大节点](https://leetcode-cn.com/problems/er-cha-sou-suo-shu-de-di-kda-jie-dian-lcof/) + +```java +class Solution { + List list = new ArrayList<>(); + + public int kthLargest(TreeNode root, int k) { + helper(root); + return list.get(list.size() - k); + } + + private void helper(TreeNode root) { + if (root == null) { + return; + } + helper(root.left); + list.add(root.val); + helper(root.right); + } +} +``` + +```java +class Solution { + int result = 0, count = 1; + + public int kthLargest(TreeNode root, int k) { + helper(root, k); + return result; + } + + private void helper(TreeNode root, int k) { + if (root == null) { + return; + } + helper(root.right, k); + if (count++ == k) { + result = root.val; + return; + } + helper(root.left, k); + } +} +``` \ No newline at end of file