- /* 由字符串建立二叉树*/
- #include <iostream>
- #include <string>
- #include <stack>
- #include <stdlib.h>
- using namespace std;
- typedef struct Tree_Node{
- char value;
- struct Tree_Node *lchild;
- struct Tree_Node *rchild;
- }Node,*Tree;
- void In_Order(Tree t)
- {
- if(!t) return;
- In_Order(t->lchild);
- cout<<(t->value);
- In_Order(t->rchild);
- }
- Tree Build_Tree(string expr)
- {
- int i=0,flag=1;
- stack<Tree> e;
- stack<char> s;
- Tree t=(Tree) malloc(sizeof(Node));
- t->value=expr[i];
- t->lchild=NULL;
- t->rchild=NULL;
- Tree p=t;
- i++;
- while(expr[i]!='/0')
- {
- switch (expr[i])
- {
- case '(':
- s.push(expr[i]);
- e.push(p);
- i++;
- flag=1;
- break;
- case ')':
- s.pop();
- e.pop();
- i++;
- break;
- case ',':
- flag=0;
- i++;
- break;
- default:
- Tree q=(Tree) malloc(sizeof(Node));
- q->value=expr[i];
- q->lchild=NULL;
- q->rchild=NULL;
- p=e.top();
- if(flag)
- {
- p->lchild=q;
- }
- else
- {
- p->rchild=q;
- }
- p=q;
- i++;
- }
- }
- return t;
- }
- int main()
- {
- string expr="A(B(D,E),C(F))";
- Tree t=Build_Tree(expr);
- In_Order(t);
- system("pause");
- }