Update 二叉树相关.md

master
Omooo 4 years ago
parent 8dc89addfd
commit d9bef64660
  1. 44
      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<Integer> 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);
}
}
```
Loading…
Cancel
Save