title: Daily practice (26): the kth largest node of the binary search tree
categories:[Swords offer]
tags:[Daily practice]
date: 2022/02/25
Daily practice (26): the kth largest node of the binary search tree
Given a binary search tree, find the value of the kth largest node in it.
Example 1:
Input: root = [3,1,4,null,2], k = 1
3
/ \
1 4
\
2
Output: 4
Example 2:
Input: root = [5,3,6,2,4,null,null,1], k = 3
5
/ \
3 6
/ \
2 4
/
1
Output: 4
limit:
1 ≤ k ≤ number of elements in binary search tree
Source: LeetCode
Link: https://leetcode-cn.com/problems/er-cha-sou-suo-shu-de-di-kda-jie-dian-lcof
Method 1: vector recursion
class Solution {
public:
vector<int> ans;
void dfs(TreeNode* root) {
if (!root) {
return;
}
dfs(root->left);
ans.push_back(root->val);
dfs(root->right);
}
int kthLargest(TreeNode* root, int k) {
dfs(root);
return ans[ans.size() - k];
}
};
Method 2: Variable recursion
Change the in-order traversal of "left-center-right" to reverse in-order traversal of "right-center-left"
It is enough to maintain two variables count and res. count is used to count how many digits we have walked in the descending sequence of numbers. When k digits have been moved, let res equal to the current root -> val, and then exit the inorder function.
class Solution {
public:
// 二叉搜索树的中序遍历是递增序列
int count, res;
void dfs(TreeNode* root, int k){
if (root == nullptr) {
return;
}
dfs(root->right, k);
count++;
if (count == k) {
res = root->val;
return;
}
dfs(root->left, k);
}
int kthLargest(TreeNode* root, int k) {
dfs(root, k);
return res;
}
};
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。