我正在尝试制作一个中缀表达式转后缀表达式的程序。我已经在Google上搜索了一些代码,但大多数算法都是使用堆栈或者使用许多正则表达式或难以理解的,但我想用二叉树来实现。
以下是我已经完成的内容:
类Node:
public class Node
{
private object element;
private Node left;
private Node right;
private Node parent;
public Node()
{
}
public Node(object x, Node r, Node l)
{
element = x;
right = r;
left = l;
}
public object GetElement()
{
return element;
}
public void SetElement(object x)
{
element = x;
}
public Node GetLeft()
{
return left;
}
public void SetLeft(Node l)
{
left = l;
}
public Node GetRight()
{
return right;
}
public void SetRight(Node r)
{
right = r;
}
public Node GetParent()
{
return parent;
}
public void SetParent(Node p)
{
parent = p;
}
}
抱歉,我使用了get/set而不是简单的自动属性。
还有我的BST类,它有插入(Insert)、后序(Postfix)、前序(Prefix)和中序(Infix)方法(我还编写了搜索、删除最小值等方法,但我们不需要它们来回答我的问题)。
BST类:
public class BinarySearchTree
{
//Node r: root.
public void Insert(Node r, Node p, object x)
{
if (r == null)
{
r = new Node(x, null, null);
r.SetParent(p);
if ((int)x < (int)p.GetElement())
p.SetLeft(r);
else if ((int)x > (int)p.GetElement())
p.SetRight(r);
}
if ((int) x < (int) r.GetElement())
Insert(r.GetLeft(), r, x);
else if ((int) x > (int) r.GetElement())
Insert(r.GetRight(), r, x);
}
public void PreOrder(Node p)
{
if (p != null)
{
Console.WriteLine(p.GetElement());
PreOrder(p.GetLeft());
PreOrder(p.GetRight());
}
}
public void Inorder(Node p)
{
if (p != null)
{
Inorder(p.GetLeft());
Console.WriteLine(p.GetElement());
Inorder(p.GetRight());
}
}
public void Postorder(Node p)
{
if (p != null)
{
Postorder(p.GetLeft());
Postorder(p.GetRight());
Console.WriteLine(p.GetElement());
}
}
}
我的插入方法适用于数字,例如:
如果我们想要编写以下树的中序遍历、先序遍历和后序遍历
前序遍历:5、3、2、4、7、6、12
后序遍历:2、4、3、6、12、7、5
中序遍历:2、3、4、5、6、7、12
此示例的主要方法:
private static void Main()
{
BinarySearchTree bst = new BinarySearchTree();
Node r = new Node(5, null, null);
bst.Insert(r, null, 3);
bst.Insert(r, null, 7);
bst.Insert(r, null, 4);
bst.Insert(r, null, 12);
bst.Insert(r, null, 2);
bst.Insert(r, null, 6);
bst.Inorder(r);
Console.WriteLine();
bst.Postorder(r);
Console.WriteLine();
bst.PreOrder(r);
}
现在我想制作一个中缀转后缀的转换器,但不知道如何实现插入方法,并如何按顺序处理运算符和操作数。另一个问题是括号。
如果您能提供一些代码帮助我,我将非常感激。
使用树的示例:
mathblog有一个中缀表达式转后缀表达式的转换器,您可以使用它来检查您的表达式。
http://www.mathblog.dk/tools/infix-postfix-converter/