【剑指offer】【树】54.二叉搜索树的第k大节点
题目链接:https://leetcode-cn.com/problems/er-cha-sou-suo-shu-de-di-kda-jie-dian-lcof/
递归
中序遍历的二叉搜索树序列为单调递增的序列,将中序遍历的结果放到vector中,第k大的数为v.size()-k位置的数
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<int> v;
void dfs(TreeNode * root)
{
if(root->left) dfs(root->left);
v.push_back(root->val);
if(root->right) dfs(root->right);
}
int kthLargest(TreeNode* root, int k) {
dfs(root);
return v[v.size() - k];
}
};
迭代
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int kthLargest(TreeNode* root, int k) {
stack<TreeNode *> st;
int i = 0;
while(!st.empty() || root)
{
while(root)
{
st.push(root);
root = root -> right;
}
root = st.top();
st.pop();
i++ ;
if(i == k) return root->val;
root = root->left;
}
return 0;
}
};
知识的价值不在于占有,而在于使用