知识大全 c#二叉树遍历vs2008实现

Posted 结点

篇首语:提兵百万西湖上,立马吴山第一峰!本文由小常识网(cha138.com)小编为大家整理,主要介绍了知识大全 c#二叉树遍历vs2008实现相关的知识,希望对你有一定的参考价值。

  下面简单介绍一下几种算法和思路

  先序遍历

   访问根结点

   按先序遍历左子树;

   按先序遍历右子树;

   例如 遍历已知二叉树结果为 A >B >D >G >H >C >E >F

  中序遍历

   按中序遍历左子树;

   访问根结点;

   按中序遍历右子树;

   例如遍历已知二叉树的结果 B >G >D >H >A >E >C >F

  后序遍历

   按后序遍历左子树;

   按后序遍历右子树;

   访问根结点;

   例如遍历已知二叉树的结果 G >H >D >B >E >F >C >A

  层次遍历

   从上到下 从左到右遍历二叉树的各个结点(实现时需要借辅助容器);

   例如遍历已知二叉树的结果 A >B >C >D >E >F >G >H

  下面只是做了一个中序遍历

  using System;

  using System Collections Generic;

  using System Linq;

  using System Text;

  namespace TreeNode_

  

  // Binary Tree的结点类

  class Node

  

  public  int Data get; set;

  public  Node LeftSubNode get; set;

  public  Node RightSubNode get; set;

  // 结点为自己追加子结点(与向左/向右追加结合 形成递归)

  public void Append(Node subNode)

  

  if (subNode Data <= this Data)

  

  this AppendLeft(subNode);

  

  else

  

  this AppendRight(subNode);

  

  

  // 向左追加

  public void AppendLeft(Node subNode)

  

  if (this LeftSubNode == null)

  

  this LeftSubNode = subNode;

  

  else

  

  this LeftSubNode Append(subNode);

  

  

  // 向右追加

  public void AppendRight(Node subNode)

  

  if (this RightSubNode == null)

  

  this RightSubNode = subNode;

  

  else

  

  this RightSubNode Append(subNode);

  

  

  // 结点显示自己的数据

  public void ShowData()

  

  Console WriteLine( Data= this Data);

  

  

  // Binary Tree类

  class Tree

  

  // 根结点

  public Node Root get; set;

  // 以某结点为起点 插入结点

  public void Insert(Node newNode)

  

  if (this Root == null)

  

  this Root = newNode;

  

  else

  

  this Root Append(newNode);

  

  

  // 重载 默认以根结点为起点插入

  public void MidTravel()

  

  this MidTravel(this Root);

  

  // 中序遍历(递归)

  public void MidTravel(Node node)

  

  if (node LeftSubNode != null)

  

  this MidTravel(node LeftSubNode);

  

  node ShowData();

  if (node RightSubNode != null)

  

  this MidTravel(node RightSubNode);

  

  

  

  class Program

  

  static void Main(string[] args)

  

  Tree tree = new Tree();

  tree Insert(new Node Data = );

  tree Insert(new Node Data = );

  tree Insert(new Node Data = );

  tree Insert(new Node Data = );

  tree Insert(new Node Data = );

  tree MidTravel();

  Console Read();

  

  

cha138/Article/program/net/201311/11814

相关参考