使用二叉树对算数表达式(以下简称为表达式)进行求值,实质上是将表达式转换为二叉树,对其进行后序遍历,得到后缀表达式的同时可以求得表达式的值。转换和求值的过程也需要借助数据结构栈的帮助。
二叉树数据结构需要声明2个类,二叉树节点类(BinaryTreeNode)和二叉树类(BinaryTree),这两个类都是模板类:
#ifndef BINARYTREE_H
#define BINARYTREE_H
template class BinaryTree;
template
class BinaryTreeNode
{
public:
friend class BinaryTree;
T _data;
private:
BinaryTreeNode * _leftChild;
BinaryTreeNode * _rightChild;
};
template
class BinaryTree
{
public:
BinaryTree()
{
_root = nullptr;
}
~BinaryTree()
{
destory();
}
void preOrder()
{
preOrder(_root);
}
void inOrder()
{
inOrder(_root);
}
void postO