由完全二叉树的层序遍历求先序、中序、后序,其中-1表示该节点处为NULL
#include<bits/stdc++.h>
using namespace std;
struct node
{
int val;
node* left;
node* right;
node(int x) : val(x), left(NULL), right(NULL) {}
};
vector<int> before;
vector<int> mid;
vector<int> back;
void dfs(node* root) {
if (!root) {
return;
}
if(root->val != -1)
before.push_back(root->val);
dfs(root->left);
if(root->val != -1)
mid.push_back(root->val);
dfs(root->right);
if(root->val != -1)
back.push_back(root->val);
}
vector<vector<int>> binaryTreeScan(int* input, int inputLen) {
vector<vector<int>> ans;
if (inputLen <= 0) return ans;
node* root = new node(input[0]);
int n = 1;
int m = 0;
queue<node*> q;
q.push(root);
while (n < inputLen) {
int cur_len = pow(2, m);
m++;
while (cur_len-- && n < inputLen) {
q.front()->left = new node(input[n++]);
q.push(q.front()->left);
q.front()->right = new node(input[n++]);
q.push(q.front()->right);
q.pop();
}
}
dfs(root);
ans.push_back(before);
ans.push_back(mid);
ans.push_back(back);
return ans;
}
void print(vector<vector<int>> arr) {
for (auto vec : arr) {
for (auto i : vec) {
cout << i << " ";
}
cout << endl;
}
}
int main() {
// int input[] = { 1, 7, 2, 6, -1, 4, 8 };
int input[] = {1, -1, 2, -1, -1, -1, 3};
vector<vector<int>> ans = binaryTreeScan(input, 7);
print(ans);
return 0;
}