using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DataStructure
{
namespace Tree
{
internal class BinaryTree
{
private Node root;
public void Insert(int data)
{
var node = new Node(data);
if (root == null)
{
root = node;
return;
}
var current = root;
while (true)
{
if (current.data > data)
{
if (current.leftChild == null)
{
current.leftChild = node;
break;
}
current = current.leftChild;
}
else if (current.data < data)
{
if (current.rightChild == null)
{
current.rightChild = node;
break;
}
current = current.rightChild;
}
}
}
public void InOrder()
{
InOrder(root);
}
public void PreOrder()
{
InOrder(root);
}
public void PostOrder()
{
InOrder(root);
}
private void InOrder(Node node)
{
if (node == null)
return;
InOrder(node.leftChild);
Console.Write(node.data);
InOrder(node.rightChild);
}
private void PreOrder(Node node)
{
if (node == null)
return;
Console.Write(node.data);
PreOrder(node.leftChild);
PreOrder(node.rightChild);
}
private void PostOrder(Node node)
{
if (node == null)
return;
PostOrder(node.leftChild);
PostOrder(node.rightChild);
Console.Write(node.data);
}
public int Height()
{
return Height(root);
}
private int Height(Node node)
{
if (node == null)
{
return -1;
}
if (IsLeaf(node))
{
return 0;
}
return 1 + Math.Max(Height(node.leftChild), Height(node.rightChild));
}
private bool IsLeaf(Node node)
{
if (node.leftChild == null && node.rightChild == null)
{
return true;
}
return false;
}
public bool IsEqual(Node first, Node second)
{
if (first == null && second == null)
return true;
if (first != null && second != null)
{
return first.data == second.data &&
IsEqual(first.rightChild, second.rightChild) &&
IsEqual(first.leftChild, second.leftChild);
}
return false;
}
}
public class Node
{
public int data;
public Node leftChild;
public Node rightChild;
public Node(int data)
{
this.data = data;
}
}
}
}