參考答案:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace CSD04
{
class Program
{
static void Main(string[] args)
{
TreeNode nodeRoot = new TreeNode()
{
Value = 2,
NodeLeft = new TreeNode()
{
Value = 7,
NodeLeft = new TreeNode() { Value = 2, NodeLeft = null, NodeRight = null },
NodeRight = new TreeNode()
{
Value = 6,
NodeLeft = new TreeNode() { Value = 5, NodeLeft = null, NodeRight = null },
NodeRight = new TreeNode() { Value = 11, NodeLeft = null, NodeRight = null }
}
},
NodeRight = new TreeNode()
{
Value = 5,
NodeLeft = null,
NodeRight = new TreeNode()
{
Value = 9,
NodeLeft = new TreeNode() { Value = 4, NodeLeft = null, NodeRight = null },
NodeRight = null
}
}
};
Tree tree = new Tree(nodeRoot);
string preorder = tree.PreorderTraversal();
string inorder = tree.InorderTraversal();
string postorder = tree.PostorderTraversal();
Console.WriteLine("前序: {0}", preorder);
Console.WriteLine("中序: {0}", inorder);
Console.WriteLine("後序: {0}", postorder);
Console.Read();
}
}
public class TreeNode
{
public int Value { get; set; }
public TreeNode NodeLeft { get; set; }
public TreeNode NodeRight { get; set; }
}
public class Tree
{
private TreeNode _root = null;
public Tree(TreeNode NodeRoot)
{
this._root = NodeRoot;
}
//TODO 主程式部分都是題庫已經打好的,重點就是以下幾個排序Function
public string PreorderTraversal()
{
return recPre(_root);
}
public string InorderTraversal()
{
return recIn(_root);
}
public string PostorderTraversal()
{
return recPost(_root);
}
private string recPre(TreeNode root)
{
if (root == null)
return null;
else
{
return root.Value+" "+recPre(root.NodeLeft) +recPre(root.NodeRight);
}
}
private string recIn(TreeNode root)
{
if (root == null)
return null;
else
{
return recIn(root.NodeLeft) + root.Value + " " + recIn(root.NodeRight);
}
}
private string recPost(TreeNode root)
{
if (root == null)
return null;
else
{
return recPost(root.NodeLeft) + recPost(root.NodeRight) + root.Value + " ";
}
}
}
}
執行結果:
留言列表