c++用二叉树表示代数表达式_表达式二叉树(C++实现,实现了通过前缀,中缀,后缀表达式构建二叉树)...

1 //表达式二叉树2 //作者:王锦3 //邮箱:[email protected]

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值