构建二叉树
需求:
- 从键盘输入二叉树的节点值;
- 根据节点值以及输入的顺序来构建二叉树并打印输出;
本二叉树的构建适用于ACM模式需要自己构造输入和输出。
#include <iostream>
#include <vector>
#include <math.h>
#include <queue>
#include <map>
#include <algorithm>
using namespace std;
// 定义二叉树
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode() :val(0), left(nullptr), right(nullptr) {}
TreeNode(int x) :val(x), left(nullptr), right(nullptr) {}
TreeNode(int x, TreeNode* left, TreeNode* right) :val(x), left(left), right(right) {}
};
// 创建二叉树
TreeNode* CreateTree(vector<int>& nums) {
vector<TreeNode*> vecTree(nums.size(), nullptr);
TreeNode* root = nullptr;
for (size_t i = 0; i < nums.size(); i++) {
TreeNode* node = nullptr;
if (nums[i] != -1)node = new TreeNode(nums[i]);
if (i == 0)root = node;
vecTree[i] = node;
}
for (int i = 0; 2 * i + 1 < nums.size(); i++) {
if (vecTree[i] != nullptr) {
vecTree[i]->left = vecTree[2 * i + 1];
if (2 * i + 2 < nums.size()) {
vecTree[i]->right = vecTree[2 * i + 2];
}
}
}
return root;
}
// 打印二叉树
void printTree(TreeNode* root) {
queue<TreeNode*> que;
vector<int> ret;
if (root != nullptr)que.push(root);
while (!que.empty()) {
int size = que.size();
for (int i = 0; i < size; i++) {
TreeNode* cur = que.front();
que.pop();
ret.push_back(cur->val);
if (cur->left != nullptr)que.push(cur->left);
if (cur->right != nullptr)que.push(cur->right);
}
}
for (int num : ret) {
cout << num << endl;
}
}
int main(int argc, char* argv[]) {
std::ios::sync_with_stdio(false);
std::cin.tie(nullptr);
vector<int> nums1;
int num1;
while (cin >> num1) {
nums1.push_back(num1);
if (cin.get() == '\n') {
break;
}
}
return 0;
}