C# binary tree search example

  • 2009
  • 0

C# binary tree search example

image

二元樹的解說參考http://zh.wikipedia.org/wiki/%E4%BA%8C%E5%8F%89%E6%A0%91

 

1.先定義節點物件

public class BinaryTreeNode
        {
            public BinaryTreeNode Left { get; set; }

            public BinaryTreeNode Right { get; set; }

            public int Data { get; set; }
            public BinaryTreeNode(int data)
            {
                this.Data = data;
            }
        }

2.使用節點物件來建立二元樹

BinaryTreeNode nodeRoot = new BinaryTreeNode("A")
           {

               Left = new BinaryTreeNode("B")
               {

                   Left = new BinaryTreeNode("D")
                   {

                       Left = new BinaryTreeNode("G"),
                       Right = null
                   },
                   Right = new BinaryTreeNode("E")
                   {

                       Left = new BinaryTreeNode("H"),
                       Right = new BinaryTreeNode("I")
                      
                   }
               },
               Right = new BinaryTreeNode("C")
               {

                   Left = null,
                   Right = new BinaryTreeNode("F")
              }
           };

3.前序訪問

Action<string> printValue = delegate(string v)
            {
                Console.Write(v + " ");
            };
            PreOrderTraversal(printValue, nodeRoot);

 

public static void PreOrderTraversal(Action<string> action, BinaryTreeNode root)
       {
           if (root == null)
               return;

           action(root.Data);
           PreOrderTraversal(action, root.Left);
           PreOrderTraversal(action, root.Right);
       }

image

 

4.中序訪問

Action<string> printValue = delegate(string v)
{
Console.Write(v + " ");
};

  InOrderTraversal(printValue, nodeRoot);

public static void InOrderTraversal(Action<string> action, BinaryTreeNode root)
      {
          if (root == null)
              return;

          InOrderTraversal(action, root.Left);
          action(root.Data);
          InOrderTraversal(action, root.Right);
      }

image


5.後序訪問

Action<string> printValue = delegate(string v)
{
Console.Write(v + " ");
};

PostOrderTraversal(printValue, nodeRoot);

public static void PostOrderTraversal(Action<string> action, BinaryTreeNode root)
      {
          if (root == null)
              return;
          PostOrderTraversal(action, root.Left);
          PostOrderTraversal(action, root.Right);
          action(root.Data);
      }

image