在C++中将preOrdered树键数放入数组中的方法如下:
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
};
void preOrder(TreeNode* root, int arr[], int& index) {
if (root == nullptr) {
return;
}
arr[index++] = root->val;
preOrder(root->left, arr, index);
preOrder(root->right, arr, index);
}
int* preOrderTraversal(TreeNode* root, int& size) {
int* arr = new int[size];
int index = 0;
preOrder(root, arr, index);
size = index;
return arr;
}
这样,我们就可以通过调用preOrderTraversal
函数来将preOrdered树键数放入数组中。函数返回的是动态分配的数组指针,需要在使用完毕后手动释放内存。
以下是一个示例的使用方法:
int main() {
// 创建一个示例树
TreeNode* root = new TreeNode(1);
root->left = new TreeNode(2);
root->right = new TreeNode(3);
root->left->left = new TreeNode(4);
root->left->right = new TreeNode(5);
int size = 5;
int* arr = preOrderTraversal(root, size);
// 输出结果数组
for (int i = 0; i < size; i++) {
cout << arr[i] << " ";
}
cout << endl;
// 释放内存
delete[] arr;
delete root->left->left;
delete root->left->right;
delete root->left;
delete root->right;
delete root;
return 0;
}
输出结果为:1 2 4 5 3,表示preOrdered树键数放入数组的顺序。
腾讯云相关产品和产品介绍链接地址:
领取专属 10元无门槛券
手把手带您无忧上云