binary tree
class Node:
def __init__(self,key):
self.left = None
self.right = None
self.val = key
root = Node(1)
root.left = Node(2);
root.right = Node(3);
root.left.left = Node(4);
binary tree
class Node:
def __init__(self,key):
self.left = None
self.right = None
self.val = key
root = Node(1)
root.left = Node(2);
root.right = Node(3);
root.left.left = Node(4);
Binary tree
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;
}
}
}
}
Copyright © 2021 Codeinu
Forgot your account's password or having trouble logging into your Account? Don't worry, we'll help you to get back your account. Enter your email address and we'll send you a recovery link to reset your password. If you are experiencing problems resetting your password contact us