Description
编写程序,输出以二叉树表示的算术表达式,若该表达式中含有括号,则在输出时应添上。
Input
按先序输入一行字符,其中#表示取消建立子树结点,即所有叶子节点均为#。
Output
输出该二叉树所表示的算术表达式(若表达式中含有括号,则在输出时应添上)。
-
Sample Input
*+a(###b#)##c##
-
Sample Output
(a+b)*c
#include<stdio.h> #include<stdlib.h> typedef struct BTNode{ char data; struct BTNode *lchild; struct BTNode *rchild; }BTNode; BTNode *CreateTree(){ BTNode *root = (BTNode*)malloc(sizeof(BTNode)); char s; s = getchar(); if(s == '#') return NULL; else{ root->data = s; root->lchild = CreateTree(); root->rchild = CreateTree(); } return root; } void PrintfTree(BTNode *root){ if(root->lchild){ PrintfTree(root->lchild); } printf("%c",root->data); if(root->rchild){ PrintfTree(root->rchild); } } int main(){ BTNode *root; root = CreateTree(); PrintfTree(root); return 0; }题解:构建二叉树,中序遍历输出二叉树。