二叉搜索树的第k大节点
递归法
中序遍历的二叉搜索树序列为单调递增的序列,将中序遍历的结果放到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;
}
};
原文地址:https://www.cnblogs.com/Trevo/p/12682819.html
时间: 2024-10-08 20:09:18