public enum Visited
{
none,
left,
right
}
public class BTreeNode
{
public BTreeNode left;
public BTreeNode right;
public int data;
public Visited visited;
}
public class BTree
{
public BTreeNode btreenode;
public Stack<BTreeNode> NodeStack=new Stack<BTreeNode>();
public BTree(BTreeNode node)
{
this.btreenode = node;
}
public void preVisit(BTreeNode node)
{
visit(node);
if (node != null)
{
preVisit(node.left);
preVisit(node.right);
}
}
public void InVisit(BTreeNode node)
{
if (node != null)
InVisit(node.left);
visit(node);
if (node != null)
InVisit(node.right);
}
public void BackVisit(BTreeNode node)
{
if (node != null)
{
BackVisit(node.left);
BackVisit(node.right);
}
visit(node);
}
public void preVisit1(BTreeNode node)
{
while (node != null || NodeStack.Count > 0)
{
if (node == null)
{
node = NodeStack.Pop();
if (node.right != null)
{
visit(node.right);
NodeStack.Push(node.right);
}
node = null;
}
else
{
visit(node);
NodeStack.Push(node);
node = node.left;
}
}
}
public void InVisit1(BTreeNode node)
{
while (node != null || NodeStack.Count > 0)
{
if (node == null)
{
node = NodeStack.Pop();
visit(node);
if (node.right != null)
{
NodeStack.Push(node.right);
}
node = null;
}
else
{
NodeStack.Push(node);
node = node.left;
}
}
}
public void BackVisit1(BTreeNode node)
{
while (node != null || NodeStack.Count>0)
{
if (node == null)
node = NodeStack.Peek();
if (node.visited == Visited.none)
{
node.visited = Visited.left;
NodeStack.Push(node);
node = node.left;
}
else if (node.visited == Visited.left)
{
node.visited = Visited.right;
NodeStack.Pop();
NodeStack.Push(node);
node = node.right;
}
else if (node.visited == Visited.right)
{
visit(node);
NodeStack.Pop();
node = null;
}
}
}
private void visit(BTreeNode node)
{
if(node!=null)
Console.Out.Write(" "+node.data);
}