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