二叉树遍历::
① NLR:前序遍历(PreorderTraversal亦称(先序遍历))
——访问根结点的操作发生在遍历其左右子树之前。
② LNR:中序遍历(InorderTraversal)
——访问根结点的操作发生在遍历其左右子树之中(间)。
③ LRN:后序遍历(PostorderTraversal)
——访问根结点的操作发生在遍历其左右子树之后。
中序遍历:左中右
后续遍历:左右中
图解见相册 aa
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ErChaShu
{
/// <summary>
/// 二叉树遍历。。。。
/// </summary>
public class Node//节点类
{
private object _nodeValue;
private Node _leftNode;
private Node _rightNode;
public object NodeValue
{
get { return this._nodeValue; }
}
public Node LeftNode
{
get {return this._leftNode; }
set {this._leftNode = value; }
}
public Node RightNode
{
get{return this._rightNode; }
set{this._rightNode = value;}
}
public Node()
{ }
public Node(object nodeValue, Node leftNode, Node rightNode)
{
this._nodeValue = nodeValue;
this._leftNode = leftNode;
this._rightNode = rightNode;
}
public Node(object nodevalue)
{
this._nodeValue = nodevalue;
this._leftNode = null;
this._rightNode = null;
}
}
public class BTree
{
private static Node root = null;
public static void CreateTree()
{
Node node1 = new Node(1, null, null);
Node node2 = new Node(2, null, null);
Node node3 = new Node(3, null, null);
Node node4 = new Node(4, null, null);
Node node5 = new Node(5, null, null);
Node node6 = new Node(6, null, null);
Node node7 = new Node(7, null, null);
node1.LeftNode = node2;
node1.RightNode = node3;
node2.LeftNode = node4;
node2.RightNode = node5;
node3.LeftNode = node6;
node3.RightNode = node7;
root = node1;
}
private static void frontList(Node node)
{
if (node == null)
{return; }
else
{ Console.WriteLine(node.NodeValue+"/t");
frontList(node.LeftNode);
frontList(node.RightNode); }
}
private static void middleList(Node node)
{
if (node == null)
{ return; }
else
{ middleList(node.LeftNode);
Console.WriteLine(node.NodeValue+"/t");
middleList(node.RightNode); }
}
private static void backList(Node node)
{
if (node == null)
{ return; }
else
{ backList(node.LeftNode);
backList(node.RightNode);
Console.WriteLine(node.NodeValue+"/t");}
}
public static void ShowList()
{
CreateTree();
Console.WriteLine("前序遍历如下:");
frontList(root);
Console.WriteLine("中序遍历如下:");
middleList(root);
Console.WriteLine("后序遍历如下:");
backList(root);
}
}
public class Demo
{
public static void Main(string[] args)
{ BTree.ShowList();
Console.ReadLine();
}
}
}