Input: - + * b# # # # # # # d#/e# # # #
Output: (a + b * (c-d) - e/f)
Binary tree diagram below!
Here is to build a binary tree with the sequence traversal, how should add parentheses output infix expression
#include
# define MAXSIZE 100
Typedef struct BiTNode
{
Char data;
Struct BiTNode * lchild;
Struct BiTNode * rchild;
} BiTNode, * BiTree;
Typedef struct/* base to the bottom of the stack pointer, top to bottom of stack pointer, insert: top++; Delete: top -; */
{
BiTree * base;
BiTree * top;
Int stacksize;
} SqStack;///definition (order stack
Void InitStack (SqStack & amp; S)///initializes the
{
S.b ase=new BiTree [MAXSIZE];
if(! S.b ase)
Printf (" \ n storage allocation failure ");
S.t op=S.b ase;
S.s tacksize=MAXSIZE;
}
Int a Push (SqStack & amp; S, BiTree e)
{
If (S.t op - S.b ase==S.s tacksize)
return 0;
* S.t op++=e;
return 1;
}
Int Pop (SqStack & amp; S, BiTree & amp; E)
{
If (S.t op==S.b ase)
return 0;
E=* - S.t op;
return 1;
}
Int StackEmpty (SqStack & amp; S)
{
If (S.t op==S.b ase)//stack empty
return 1;
The else
return 0;
}
BiTree GetTop (SqStack S) {
//return S of stack elements, do not change the stack pointer
If (S.t op!=S.b ase)//stack is not empty
Return * (S.t op - 1);//returns the value of the stack elements, the stack pointer constant
}
Void PreCreatBiTree (BiTree & amp; T)///first order create
{
///in accordance with the first sequence order input the value of the node in the binary tree (a character), creating a binary list according to binary tree T;
char ch;
The scanf (" % c ", & amp; Ch);
If (ch=='#')
T=NULL;
The else
{
T=new BiTNode;
T - & gt; data=https://bbs.csdn.net/topics/ch;
PreCreatBiTree (T - & gt; Lchild);
PreCreatBiTree (T - & gt; Rchild);
}
}
Void MidOrderTraverse (BiTree & amp; T)///the non-recursive algorithm sequence traversal in
{
SqStack S;
BiTree q, p;
InitStack (S);///initializes a empty stack
P=T;///a pointer points to the root node p
Q=new BiTNode;///q, apply for a node space used to store the stack pop-up element
Printf (" (");
While (p | |! StackEmpty (S))///(when p is not empty or stack S not empty)
{
If (p)//p is not empty
{
Push (S, p);//root stack pointer into
P=p - & gt; Lchild;//root needle into the stack, traverse the left subtree
}
The else//p is empty
{
Pop (S, q);//return stack
Printf (" % c ", q - & gt; The data);//access to the root node
P=q - & gt; Rchild;//traverse right subtree
}
}
Printf (") ");
}
Int main ()
{
BiTree T;
PreCreatBiTree (T);
MidOrderTraverse (T);
return 0;
}
CodePudding user response:
I hope it can help you: https://blog.csdn.net/it_xiangqiang/category_10581430.html
I hope it can help you: https://blog.csdn.net/it_xiangqiang/category_10768339.html