一、寒假作业1-树与二叉树
笔者认为老师题目不严谨,明明是
所以笔者把所有都求了一遍
答案如下
2. (程序题) 键盘输入广义表形式输出的二叉树字符串,例如输入 A(B(D,E),C(,F)))
按照输入的字符规律建立二叉树,提示使用栈作为辅助。
二叉树中序遍历的次序输出。
输入:A(B(D,E),C(,F))
输出:二叉树中序遍历:D B E A C F
#include <stdio.h>
#include <stdlib.h>
#include <stack>
using namespace std;
typedef struct BinNode{
char data;
struct BinNode *left;
struct BinNode *right;
}BinNode,*BinTree;
void BinTreeInit(BinTree &T){
T = NULL;
T->left = T->right = NULL;
}
//中序遍历
void InOrder(BinTree &T){
if(T!=NULL){
InOrder(T->left);
printf("%c ",T->data);
InOrder(T->right);
}
}
CreateBinTree(BinTree &T,char str[]){
int i = 0,k = 0;//k=0为根,k=-1为左子树,k=1为右子树
stack<BinNode*>num;//存储字母
//stack<BinNode*>opt;//存储符号
while(!num.empty()) num.pop();
int flag = 1;
int flag2 = 1;
while(str[i] != '\0'){
switch(str[i]){
case ' ': break;
case '(': flag = 0;
k = -1;
break;
case ',': k = 1;
flag2 = 0;
if(flag!=0) num.pop();
break;
case ')':
if(flag2!=0) num.pop();
break;
default: BinNode *tmp = new BinNode{str[i]};
flag = 1;
flag2 = 1;
switch(k){
case 0: num.push(tmp);
T = num.top();
break;
case -1: num.top()->left = tmp;
num.push(tmp);
break;
case 1: num.top()->right = tmp;
num.push(tmp);
}
}
i++;
}
}
int main(){
BinTree T;
//BinTreeInit(T);
char str[100];
scanf("%s",str);
CreateBinTree(T,str);
printf("二叉树中序遍历:");
InOrder(T);
return 0;
}