二叉树非递归遍历算法
遍历算法如下:
using System;
using System.Collections.Generic;
using System.Text;
namespace Tree
{
public delegate void Visitor(TreeNode node);
public class TreeVisitor
{
private Visitor visit = null;
public TreeVisitor(Visitor v)
{
this.visit = v;
}
/// <summary>
/// 中序遍历
/// </summary>
/// <param name="root"></param>
public void BT_InOrderNoRec(TreeNode root)
{
TreeStack nodes = new TreeStack();
while (root != null || nodes.Count != 0)
{
if (root != null)
{
nodes.Push(root);
root = root.LChild;
}
else
{
root = nodes.Pop();
this.visit(root);
root = root.RChild;
}
}
}
/// <summary>
/// 前序遍历
/// </summary>
/// <param name="root"></param>
public void BT_PreOrderNoRec(TreeNode root)
{
TreeStack nodes = new TreeStack();
while (root != null || nodes.Count != 0)
{
if (root != null)
{
this.visit(root);
nodes.Push(root);
root = root.LChild;
}
else
{
root = nodes.Pop();
root = root.RChild;
}
}
}
/// <summary>
/// 后序遍历
/// </summary>
/// <param name="root"></param>
public void BT_BckOrderNoRec(TreeNode root)
{
TagNodeStack nodes = new TagNodeStack();
while (root != null || nodes.Count != 0)
{
while (root != null)
{
TagNode node = new TagNode(root);
nodes.Push(node);
root = root.LChild;
}
while (nodes.Count != 0 && nodes.Peek().Tag)
{
this.visit(nodes.Pop().Node);
}
if (nodes.Count > 0)
{
TagNode temp = nodes.Pop();
temp.Tag = true;
nodes.Push(temp);
root = temp.Node.RChild;
}
}
}
}
}
class TreeNodeFactory
{
public static TreeNode CreateRoot(string content)
{
TreeNode root = new TreeNode();
root.Content = content;
return root;
}
public static TreeNode CreateLeftChild(TreeNode parent, string content)
{
TreeNode lChild = new TreeNode(parent);
lChild.Content = content;
parent.LChild = lChild;
return lChild;
}
public static TreeNode CreateRightChild(TreeNode parent, string content)
{
TreeNode rChild = new TreeNode(parent);
rChild.Content = content;
parent.RChild = rChild;
return rChild;
}
}
class Program
{
static void Main(string[] args)
{
TreeNode root = TreeNodeFactory.CreateRoot("A");
TreeNode lchild = TreeNodeFactory.CreateLeftChild(root, "B");
TreeNode rchild = TreeNodeFactory.CreateRightChild(root, "C");
TreeNodeFactory.CreateLeftChild(lchild, "D");
TreeNodeFactory.CreateRightChild(lchild, "E");
TreeVisitor myVisitor = new TreeVisitor(new Program().VisitNode);
myVisitor.BT_InOrderNoRec(root);
Console.WriteLine();
myVisitor.BT_PreOrderNoRec(root);
Console.WriteLine();
myVisitor.BT_BckOrderNoRec(root);
Console.Read();
}
private void VisitNode(TreeNode node)
{
Console.Write("\t"+node.Content);
}
}


浙公网安备 33010602011771号