题目描述
根据完整先序遍历构造二叉树
C++ 代码
#include<iostream>
using namespace std;
char s[100];
int idx=0;
//由先序遍历建树
struct TreeNode{
char val;
TreeNode* left,*right;
TreeNode(char x): val(x),left(NULL),right(NULL){};
};
TreeNode* Create(){
char n=s[idx++];
if(n=='#') return NULL;
auto root = new TreeNode(n);
root->left=Create();
root->right=Create();
return root; //记得return
}
void inorder(TreeNode* root){
if(!root) return;
inorder(root->left);
cout << root->val << " ";
inorder(root->right);
}
int main(){
cin >> s;
auto root = Create();
inorder(root);
return 0;
}