1. 程式人生 > >二叉樹和廣義表的轉換

二叉樹和廣義表的轉換

def har out char emp typedef con 逗號 字符串

  1 //廣義表轉二叉樹:
  2 設置一個標記變量k,初始值為-1  3 設置一個標記結點p;
  4 循環遍歷廣義表的字符串str;
  5     如果str[i]是左括號:
  6         則設置k為0;
  7         把p壓入棧中。
  8     否則如果str[i]是逗號:
  9         則設置k為1。
 10     否則如果str[i]是右括號:
 11         則棧頂元素出棧。
 12     否則如果str[i]是一個字母,用結點temp來存儲:
 13         如果k為-1 14             則把temp作為根結點並壓入棧中。
15 如果k為0: 16 如果此時棧頂結點是p,則先出棧; 17 然後將temp作為棧頂結點的左孩子; 18 再把temp壓入棧中。 19 如果k為1: 20 棧頂元素出棧; 21 將temp作為棧頂結點的右孩子; 22 再把temp壓入棧中。 23 24 25 struct Node{ 26 char data; 27 Node *lchild=NULL,*rchild=NULL;
28 }; 29 30 typedef struct Node node; 31 32 node* build(const string &str){ 33 node *root = NULL; 34 unsigned long max_length=str.length(); 35 int k=-1; 36 int top=-1; 37 node *p; 38 node *temp; 39 node* Stack[max_length]; 40 for(int i=0;i<max_length;i++){
41 if(str[i]==(){ 42 k=0; 43 top++; 44 Stack[top]=p; 45 } 46 else if(str[i]==,){ 47 k=1; 48 } 49 else if(str[i]==)){ 50 top--; 51 } 52 else if(isalpha(str[i])){ 53 temp=new node; 54 temp->data=str[i]; 55 if(k==-1){ 56 root=temp; 57 top++; 58 Stack[top]=temp; 59 } 60 else if(k==0){ 61 if(Stack[top]==p){ 62 top--; 63 } 64 Stack[top]->lchild=temp; 65 top++; 66 Stack[top]=temp; 67 } 68 else if(k==1){ 69 top--; 70 Stack[top]->rchild=temp; 71 top++; 72 Stack[top]=temp; 73 } 74 } 75 } 76 return root; 77 } 78 79 80 81 82 //二叉樹轉廣義表 83 輸出結點存儲的值; 84 如果左孩子不為空: 85 輸出"(" 86 遞歸輸出左子樹; 87 如果右子樹為空: 88 輸出",)" 89 如果右孩子不為空: 90 如果左孩子為空: 91 輸出"(" 92 輸出"," 93 遞歸輸出右子樹; 94 輸出")" 95 96 97 void print_list(node* cur_node){ 98 cout<<cur_node->data; 99 if(cur_node->lchild!=NULL){ 100 cout<<"("; 101 print_list(cur_node->lchild); 102 if(cur_node->rchild==NULL){ 103 cout<<",)"; 104 } 105 } 106 if(cur_node->rchild!=NULL){ 107 if(cur_node->lchild==NULL){ 108 cout<<"("; 109 } 110 cout<<","; 111 print_list(cur_node->rchild); 112 cout<<")"; 113 } 114 }

二叉樹和廣義表的轉換