手动创建二叉树-ACM模式
Posted 每天告诉自己要努力
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了手动创建二叉树-ACM模式相关的知识,希望对你有一定的参考价值。
按层序遍历创建create
打印的话可以任意选择一种方式打印,这里选层序了,方便直观
要是改成前序的话更简单,把print函数改成递归的前序遍历就可以了
#include <bits/stdc++.h>
using namespace std;
struct TreeNode
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x) : val(x), left(nullptr), right(nullptr)
;
TreeNode* create(const vector<int> &vec)
vector<TreeNode*> vecTree(vec.size(), nullptr);
TreeNode* root = nullptr;
for (int i = 0; i < vec.size(); i++)
TreeNode* node = nullptr;
if (vec[i] != -1) node = new TreeNode(vec[i]);
vecTree[i] = node;
if (i == 0) root = node;
for (int i = 0; i * 2 + 2 < vec.size(); i++)
if (vecTree[i] != nullptr)
vecTree[i]->left = vecTree[i * 2 + 1];
vecTree[i]->right = vecTree[i * 2 + 2];
return root;
void print(TreeNode* root)
if (!root) return;
queue<TreeNode*> que;
que.push(root);
vector<vector<int>> res;
while (!que.empty())
int size = que.size();
vector<int> vec;
for (int i = 0; i < size; i++)
TreeNode* node = que.front();
que.pop();
if (node)
vec.push_back(node->val);
que.push(node->left);
que.push(node->right);
else
vec.push_back(-1);
res.push_back(vec);
for (int i = 0; i < res.size(); i++)
for (int j = 0; j < res[i].size(); j++)
cout << res[i][j] << " ";
cout << endl;
int main()
//按层序遍历输入,空节点用-1代替
vector<int> vec = ………………;
TreeNode* root = create(vec);
print(root);
return 0;
需要输入:{4,2,7,1,3,6,9}
按前序遍历输入和打印
#include <bits/stdc++.h>
using namespace std;
struct TreeNode
int val;
TreeNode* left = NULL;
TreeNode* right = NULL;
TreeNode(int val) : val(val), left(NULL), right(NULL)
;
void create(TreeNode **root)
int num;
cin >> num;
if (num == -1) return;
*root = new TreeNode(num);
create(&((*root)->left));
create(&((*root)->right));
void print(TreeNode* root)
if (!root)
cout << -1 << " ";
return;
cout << root->val << " ";
print(root->left);
print(root->right);
int main()
TreeNode *root = nullptr;
create(&root);
print(root);
return 0;
需要输入:4 2 1 -1 -1 3 -1 -1 7 6 -1 -1 9 -1 -1
以上是关于手动创建二叉树-ACM模式的主要内容,如果未能解决你的问题,请参考以下文章