1 //表达式二叉树2 //作者:王锦3 //邮箱:jinksw@vip.qq.com
4
5 #include "stdafx.h"
6 #include
7 #include
8 #include
9 #include
10 #include
11 #include
12 #include
13 using namespacestd;14
15
16 //二叉树结点类
17 template
18 classBinaryTreeNode19 {20 private:21 T value;22 BinaryTreeNode *leftChild;23 BinaryTreeNode *rightChild;24 public:25 BinaryTreeNode(){leftChild = NULL,rightChild =NULL;};26 BinaryTreeNode(const T&mValue);27 BinaryTreeNode(const T&mValue,BinaryTreeNode *mLeftChild,BinaryTreeNode *mRightChild);28
29 void setValue(const T&mValue);30 T getValue()const;31
32 BinaryTreeNode * getLeftChild()const;33 BinaryTreeNode * getRightChild()const;34 void setLeftChild(BinaryTreeNode *leftChild);35 void setRightChild(BinaryTreeNode *rightChild);36
37 bool isLeaf()const;38 };39 template
40 BinaryTreeNode::BinaryTreeNode(const T&mValue)41 {42 value =mValue;43 leftChild = rightChild =NULL;44 }45
46 template
47 BinaryTreeNode::BinaryTreeNode(const T&mValue,BinaryTreeNode *mLeftChild,BinaryTreeNode *mRightChild)48 {49 value =mValue;50 leftChild =mLeftChild;51 rightChild =mRightChild;52 }53
54 template
55 T BinaryTreeNode::getValue()const//得到该结点的值
56 {57 returnvalue;58 }59
60 template
61 BinaryTreeNode* BinaryTreeNode::getLeftChild()const//得到左子结点
62 {63 returnleftChild;64 }65
66 template
67 BinaryTreeNode* BinaryTreeNode::getRightChild()const//得到右子结点
68 {69 returnrightChild;70 }71
72 template
73 void BinaryTreeNode::setLeftChild(BinaryTreeNode *leftChild)//设置左子结点
74 {75 this->leftChild =leftChild;76 }77
78 template
79 void BinaryTreeNode::setRightChild(BinaryTreeNode *rightChild)//设置右子结点
80 {81 this->rightChild =rightChild;82 }83
84 template
85 void BinaryTreeNode::setValue(const T&mValue)//设置该结点的值
86 {87 value =mValue;88 }89
90 template
91 bool BinaryTreeNode::isLeaf()const//是否为树叶
92 {93 return leftChild == NULL && rightChild ==NULL;94 }95
96 classExpressionBinaryTree97 {98 private:99 BinaryTreeNode *root;100 voidclear()101 {102 if(root ==NULL)103 return;104 recursionDeleteAll(root);105 };//调用内部递归函数清空二叉树,以及释放空间
106 bool aIsGreaterOrEqualThanB(char a,char b);//工具方法,用于比较a,b优先级
107 int getHeight(BinaryTreeNode *root);//求树的高度
108 void printBlank(int n);//工具方法,打印n个空格
109 void printInRightFormat(string value);//按照格式打印,以便对齐
110 void recursionPrintPreffixE(BinaryTreeNode *root);//递归调用打印前缀表达式
111 void recursionPrintSuffixE(BinaryTreeNode *root);//递归调用打印后缀表达式
112 bool shouldPrintLeftBracket(const stack*> &nodeStack ,BinaryTreeNode *pointer,int leftOrRight);//用于输出中缀表达式时判断是否需要输出左括号
113 void recursionD