#include<iostream>
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) {}
};
void preOrder(TreeNode* t){
if (t == NULL)
return;
cout << t->val << " ";
preOrder(t->left);
preOrder(t->right);
}
void CreateTree(TreeNode*& T, vector<int> v, int &i){
if (v[i] == -1) {
T = NULL;
i++;
}
else{
T = new TreeNode(v[i]);
if (i == v.size() - 1) return;
i++;
CreateTree(T->left, v, i);
CreateTree(T->right, v, i);
}
}
int main(){
TreeNode* root;
vector<int>v = { 1,2,4,-1,-1,5,-1,-1,3,6,-1,-1,7,-1,-1 };
int i = 0;
CreateTree(root, v, i);
preOrder(root);
return 0;
}
|