输入数组是一棵树的层序遍历,返回重建的二叉树,递归方法。
测试样例;
11
3 9 20 -1 -1 15 7 -1 -1 -1 -1
中序遍历答案
9 3 15 20 7
#include<iostream>
#include<queue>
using namespace std;
int n, num;
struct TreeNode
{
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int _val) : val(_val), left(nullptr), right(nullptr) {}
};
void dfs(TreeNode* root)
{
if (!root) return;
dfs(root->left);
cout << root->val << ' ';
dfs(root->right);
}
TreeNode* make(int p[], int u)
{
if (u > n || p[u] == -1) return nullptr;
TreeNode* root = new TreeNode(p[u]);
root->left = make(p, u * 2);
root->right = make(p, u * 2 + 1);
return root;
}
int main()
{
cin >> n;
int p[n + 1];
for (int i = 1; i <= n; i ++ ) cin >> p[i];
TreeNode* root = make(p, 1);
dfs(root);
return 0;
}