06
#include <iostream>
#include <vector>
using namespace std;
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
vector<int> vec;
void transfer(TreeNode* root) {
if (root == NULL) return;
transfer(root->left);
vec.push_back(root->val);
transfer(root->right);
}
int main() {
TreeNode* root = new TreeNode(10);
root->left = new TreeNode(5);
root->right = new TreeNode(15);
root->left->left = new TreeNode(3);
root->left->right = new TreeNode(7);
root->right->left = new TreeNode(12);
root->right->right = new TreeNode(18);
transfer(root);
int k;
cin>>k;
for(int i=vec.size()-1;i>=0;i--)
{
if(vec[i]>=k)
{
cout<<vec[i]<<" ";
}
}
return 0;
}
10
#include <iostream>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
int count; // 记录以该节点为根的子树的节点数
TreeNode(int x) : val(x), left(nullptr), right(nullptr), count(1) {}
};
// 统计以node为根结点的子树的结点数
int countNodeNum(TreeNode* node) {
if (node == NULL) {
return 0;
}
node->count = 1 + countNodeNum(node->left) + countNodeNum(node->right);
return node->count;
}
// 查找第k小的元素
int findKthSmallest(TreeNode* node, int k) {
while (node != nullptr) {
int leftCount = (node->left ) ? node->left->count : 0;
if (leftCount < k - 1) {
node = node->right;
k -= leftCount + 1;
} else if (leftCount == k - 1) {
break;
} else {
node = node->left;
}
}
return node->val;
}
int kthSmallest(TreeNode* root, int k) {
countNodeNum(root);
return findKthSmallest(root, k);
}
int main() {
// 创建测试用例
TreeNode* root = new TreeNode(5);
root->left = new TreeNode(3);
root->right = new TreeNode(7);
root->left->left = new TreeNode(2);
root->left->right = new TreeNode(4);
root->right->left = new TreeNode(6);
root->right->right = new TreeNode(8);
root->left->left->left = new TreeNode(1);
root->left->right->right = new TreeNode(4);
cout<<kthSmallest(root,3);
return 0;
}