Binary Tree depth-first Traversal

Source: Internet
Author: User
/// <Summary>
/// Binary Tree node class
/// </Summary>
Public class BinaryTreeNode
{
Object _ data;
BinaryTreeNode _ left;
BinaryTreeNode _ right;

Public BinaryTreeNode Left
{
Get
{
Return this. _ left;
}
Set
{
This. _ left = value;
}
}
Public BinaryTreeNode Right
{
Get
{
Return this. _ right;
}
Set
{
This. _ right = value;
}
}

Public BinaryTreeNode (object data)
{
This. _ data = data;
}

Public override string ToString ()
{
Return (null = _ data )? String. Empty: _ data. ToString ();
}
}


/// <Summary>

/// Binary tree collection class
/// </Summary> publicclass BinaryTree
{
BinaryTreeNode _ head;
String _ strBinaryTree;

Public BinaryTreeNode Head
{
Get
{
Return this. _ head;
}
}
Void AddNode (BinaryTreeNode parent, int index)
{
Int leftIndex = index * 2 + 1;
If (leftIndex <_ strBinaryTree. Length)
{
If (_ strBinaryTree [leftIndex]! = '*')
{
Parent. Left = new BinaryTreeNode (_ strBinaryTree [leftIndex]);
AddNode (parent. Left, leftIndex );
}
}
Int rightIndex = index * 2 + 2;
If (rightIndex <_ strBinaryTree. Length)
{
If (_ strBinaryTree [rightIndex]! = '*')
{
Parent. Right = new BinaryTreeNode (_ strBinaryTree [rightIndex]);
AddNode (parent. Right, rightIndex );
}
}
}
Public void PerOrder (BinaryTreeNode node)
{
If (null! = Node)
{
Console. Write (node );
PerOrder (node. Left );
PerOrder (node. Right );
}
}
Public void MidOrder (BinaryTreeNode node)
{
If (null! = Node)
{
MidOrder (node. Left );
Console. Write (node );
MidOrder (node. Right );
}
}
Public void AfterOrder (BinaryTreeNode node)
{
If (null! = Node)
{
AfterOrder (node. Left );
AfterOrder (node. Right );
Console. Write (node );
}
}
Public BinaryTree (string constructStr)
{
_ StrBinaryTree = constructStr;
_ Head = (string. IsNullOrEmpty (_ strBinaryTree ))? Null: new BinaryTreeNode (_ strBinaryTree [0]);
AddNode (_ head, 0 );
}
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.