Write a program to find the maximum height of a Binary tree
Solution:
using System;
namespace Pattern
{
class Program
{
public static void Main()
{
var binaryTree = new BinaryTree<int>();
binaryTree.Root = new Node<int>(1);
binaryTree.Root.Left = new Node<int>(2);
binaryTree.Root.Right = new Node<int>(3);
binaryTree.Root.Left.Left = new Node<int>(4);
binaryTree.Root.Right.Left = new Node<int>(5);
binaryTree.Root.Right.Right = new Node<int>(6);
Console.WriteLine(binaryTree.FindHeight(binaryTree.Root));
Console.ReadLine();
}
}
public class BinaryTree<T>
{
public Node<T> Root;
public BinaryTree()
{
Root = null;
}
public int FindHeight(Node<T> node)
{
if (Root == null)
{
Console.WriteLine("Tree is empty");
return 0;
}
int leftHeight = 0, rightHeight = 0;
if (node.Left != null)
leftHeight = FindHeight(node.Left);
if (node.Right != null)
rightHeight = FindHeight(node.Right);
var max = leftHeight > rightHeight ? leftHeight : rightHeight;
return max + 1;
}
}
public class Node<T>
{
public T Data;
public Node<T> Left;
public Node<T> Right;
public Node(T data)
{
Data = data;
Left = null;
Right = null;
}
}
}