#include<iostream>
#include<vector>
#include<queue>
using namespace std;
class TreeNode {
public:
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int value) : val(value), left(nullptr), right(nullptr) {
}
};
TreeNode* BulidTreeNode(vector<int>& vec, int index) {
if (index >= vec.size() || vec[index] == -1) {
return nullptr;
}
TreeNode* root = new TreeNode(vec[index]);
root->left = BulidTreeNode(vec, index * 2 + 1);
root->right = BulidTreeNode(vec, index * 2 + 2);
return root;
}
void MidSearch(TreeNode* root) {
if (root == nullptr) {
return;
}
MidSearch(root->left);
cout << root->val << endl;
MidSearch(root->right);
}
void BFS(TreeNode* root) {
bool leaf = false;
TreeNode* l = root;
TreeNode* r = root;
queue<TreeNode* > que;
que.push(root);
while (!que.empty()) {
for (int i = 0; i < que.size(); i++) {
TreeNode* temp = que.front();
cout << temp->val << endl;
que.pop();
if (temp->left) {
que.push(temp->left);
}
if (temp->right) {
que.push(temp->right);
}
}
}
}
int main() {
int n;
cin >> n;
vector<int> vec;
for (int i = 0; i < n; i++) {
int num;
cin >> num;
vec.push_back(num);
}
TreeNode* root = BulidTreeNode(vec, 0);
MidSearch(root);
cout << "++++++++++++++++++++++" << endl;
BFS(root);
return 0;
}
二叉树的层序遍历
最新推荐文章于 2024-11-14 19:11:37 发布