1. 程式人生 > 實用技巧 >重新整理資料結構與演算法(c#系列)—— 樹的前中後序遍歷[十六]

重新整理資料結構與演算法(c#系列)—— 樹的前中後序遍歷[十六]

前言

理論文章:

直接看百度百科。

這個比較簡單,直接放c#程式碼。

正文

建立節點模型:

public class HeroNode
{
	private int no;

	private string name;

	private HeroNode left;

	private HeroNode right;

	public HeroNode(int no, string name) {
		this.no = no;
		this.name = name;
	}

	public int getNo() {
		return no;
	}
	public void setNo(int no)
	{
		this.no = no;
	}

	public String getName()
	{
		return name;
	}
	public void setName(String name)
	{
		this.name = name;
	}
	public HeroNode getLeft()
	{
		return left;
	}
	public void setLeft(HeroNode left)
	{
		this.left = left;
	}
	public HeroNode getRight()
	{
		return right;
	}
	public void setRight(HeroNode right)
	{
		this.right = right;
	}
	public override string ToString()
	{
		return "姓名:" + name + "編號:" + no;
	}
	//編寫前序遍歷的方法 是根、左、右
	public void preOrder() {
		Console.WriteLine(this);

		if (this.left != null)
		{
			this.left.preOrder();
		}
		if (this.right != null)
		{
			this.right.preOrder();
		}
	}
	//中序遍歷 是左、根、右
	public void infixOrder() {
		if (this.left != null)
		{
			this.left.preOrder();
		}
		Console.WriteLine(this);
		if (this.right != null)
		{
			this.right.preOrder();
		}
	}
	// 後續遍歷為 左、右、根
	public void postOrder()
	{
		if (this.left != null)
		{
			this.left.preOrder();
		}
		if (this.right != null)
		{
			this.right.preOrder();
		}
		Console.WriteLine(this);
	}
}

建立樹模型:

public class BinaryTree
{
	private HeroNode root;

	public void setRoot(HeroNode root)
	{
		this.root = root;
	}
	//前序遍歷
	public void preOrder()
	{
		if (this.root != null)
		{
			this.root.preOrder();
		}
		else
		{
			Console.WriteLine("二叉樹為空,無法遍歷");
		}
	}

	//中序遍歷
	public void infixOrder()
	{
		if (this.root != null)
		{
			this.root.infixOrder();
		}
		else
		{
			Console.WriteLine("二叉樹為空,無法遍歷");
		}
	}
	//後序遍歷
	public void postOrder()
	{
		if (this.root != null)
		{
			this.root.postOrder();
		}
		else
		{
			Console.WriteLine("二叉樹為空,無法遍歷");
		}
	}
}

測試:

static void Main(string[] args)
{
	//先需要建立一顆二叉樹
	BinaryTree binaryTree = new BinaryTree();
	//建立需要的結點
	HeroNode root = new HeroNode(1, "宋江");
	HeroNode node2 = new HeroNode(2, "吳用");
	HeroNode node3 = new HeroNode(3, "盧俊義");
	HeroNode node4 = new HeroNode(4, "林沖");
	HeroNode node5 = new HeroNode(5, "關勝");
	//設定節點
	root.setLeft(node2);
	root.setRight(node3);
	node3.setRight(node4);
	node3.setLeft(node5);
	binaryTree.setRoot(root);
	//前序遍歷
	Console.WriteLine("前序遍歷");
	binaryTree.preOrder();
	Console.WriteLine("中序遍歷");
	binaryTree.infixOrder();
	Console.WriteLine("後續遍歷");
	binaryTree.postOrder();
	Console.ReadKey();
}

結果: