创建一二叉树

来源:互联网 发布:巴基实力 知乎 编辑:程序博客网 时间:2024/05/04 15:10

在建立二叉树的过程中,不能直接读取cin的输入,那样会一直阻塞在读取,下面是通过前序遍历读取的代码,注意在调用的root的时候引用。

#include<iostream>#include<string>using namespace std;struct treeNode{char val;struct treeNode *left;struct treeNode *right;};char str[] = "123###3##";int index = 0;void creat(treeNode *&root){char a;a = str[index++];if (a == '\0')return;if (a == '#')root = NULL;else{root = new treeNode;root->val = a;creat(root->left);creat(root->right);}}void print(treeNode *root){if (root == NULL)return;cout << root->val << endl;print(root->left);print(root->right);}int main(){treeNode *root = NULL;creat(root);print(root);}


0 0