C#实现二叉树的遍历
标签:c# 遍历 二叉树 递归 循环
C#实现二叉树的前序、中序、后序遍历。
public class BinaryTreeNode
{
int value;
BinaryTreeNode left;
BinaryTreeNode right;
///
/// 前序遍历
///
///
public static void PreOrder(BinaryTreeNode tree)
{
if (tree == null)
return;
System.Console.Write(tree.value + " ");
PreOrder(tree.left);
PreOrder(tree.right);
}
///
/// 前序遍历循环实现
///
///
public static void PreOrderLoop(BinaryTreeNode tree)
{
if (tree == null)
return;
Stack stack = new Stack();
BinaryTreeNode node = tree;
while(node != null || stack.Any()){
if(node != null)
{
stack.Push(node);
System.Console.Write(node.value + " ");
node = node.left;
}
else
{
var item = stack.Pop();
node = item.right;
}
}
}
///
/// 中序遍历
///
///
public static void InOrder(BinaryTreeNode tree)
{
if (tree == null)
return;
InOrder(tree.left);
System.Console.Write(tree.value + " ");
InOrder(tree.right);
}
///
/// 中序遍历循环实现
///
///
public static void InOrderLoop(BinaryTreeNode tree)
{
if (tree == null)
return;
Stack stack = new Stack();
BinaryTreeNode node = tree;
while (node != null || stack.Any())
{
if (node != null)
{
stack.Push(node);
node = node.left;
}
else
{
var item = stack.Pop();
System.Console.Write(item.value + " ");
node = item.right;
}
}
}
///
/// 后序遍历
///
///
public static void PostOrder(BinaryTreeNode tree)
{
if (tree == null)
return;
PostOrder(tree.left);
PostOrder(tree.right);
System.Console.Write(tree.value + " ");
}
///
/// 后序遍历循环实现1
///
///
public static void PostOrderLoop(BinaryTreeNode tree)
{
if (tree == null)
return;
Stack stack = new Stack();
BinaryTreeNode node = tree;
BinaryTreeNode pre = null;
stack.Push(node);
while (stack.Any())
{
node = stack.Peek();
if ((node.left == null && node.right == null) ||
(pre != null && (pre == node.left || pre == node.right)))
{
System.Console.Write(node.value + " ");
pre = node;
stack.Pop();
}
else
{
if (node.right != null)
stack.Push(node.right);
if (node.left != null)
stack.Push(node.left);
}
}
}
///
/// 后续遍历循环实现2
///
///
public static void PostOrderLoop2(BinaryTreeNode tree)
{
HashSet visited = new HashSet();
Stack stack = new Stack();
BinaryTreeNode node = tree;
while (node != null || stack.Any())
{
if (node != null)
{
stack.Push(node);
node = node.left;
}
else
{
var item = stack.Peek();
if (item.right != null && !visited.Contains(item.right))
{
node = item.right;
}
else
{
System.Console.Write(item.value + " ");
visited.Add(item);
stack.Pop();
}
}
}
}
}
本文出自 “许大树” 博客,请务必保留此出处http://abelxu.blog.51cto.com/9909959/1966963
C#实现二叉树的遍历
标签:c# 遍历 二叉树 递归 循环
原文地址:http://abelxu.blog.51cto.com/9909959/1966963
文章来自:
搜素材网的
编程语言模块,转载请注明文章出处。
文章标题:
C#实现二叉树的遍历
文章链接:http://soscw.com/index.php/essay/85059.html
评论