由字符串建立二叉树

 

  1. /*  由字符串建立二叉树*/
  2. #include <iostream>
  3. #include <string>
  4. #include <stack>
  5. #include <stdlib.h>
  6. using namespace std;
  7. typedef struct Tree_Node{
  8.        char value;
  9.        struct Tree_Node *lchild;
  10.        struct Tree_Node *rchild;
  11.        }Node,*Tree;
  12. void In_Order(Tree t)
  13. {
  14.      if(!t) return;
  15.      In_Order(t->lchild);
  16.      cout<<(t->value);
  17.      In_Order(t->rchild);
  18. }
  19.      
  20. Tree Build_Tree(string expr)
  21. {
  22.     
  23.      int i=0,flag=1;
  24.      stack<Tree> e;
  25.      stack<char> s;
  26.      Tree  t=(Tree) malloc(sizeof(Node));
  27.      t->value=expr[i];
  28.      t->lchild=NULL;
  29.      t->rchild=NULL;
  30.      Tree p=t;
  31.      i++;
  32.      while(expr[i]!='/0')
  33.      {
  34.          switch (expr[i]) 
  35.          {    
  36.               case '(':
  37.                    s.push(expr[i]);
  38.                    e.push(p);
  39.                    i++;
  40.                    flag=1;
  41.                    break;
  42.               case ')':
  43.                    s.pop();
  44.                    e.pop();
  45.                    i++;
  46.                    break;
  47.               case ',':
  48.                    flag=0;
  49.                    i++;
  50.                    break;
  51.               default:
  52.                    Tree q=(Tree) malloc(sizeof(Node));
  53.                    q->value=expr[i];
  54.                    q->lchild=NULL;
  55.                    q->rchild=NULL;
  56.                    p=e.top();
  57.                    if(flag)
  58.                    {
  59.                         p->lchild=q;
  60.                    }
  61.                    else
  62.                    {
  63.                        p->rchild=q;
  64.                    }
  65.                    p=q;
  66.                    i++;
  67.                             
  68.          }
  69.      }
  70.      return t;
  71.      
  72. int main()
  73. {
  74.     string expr="A(B(D,E),C(F))";
  75.     Tree t=Build_Tree(expr);
  76.     In_Order(t);
  77.     system("pause");
  78. }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值