-
Notifications
You must be signed in to change notification settings - Fork 0
/
FindMinimum&MaximumBinaryTree.cs
65 lines (55 loc) · 1.48 KB
/
FindMinimum&MaximumBinaryTree.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
using System;
namespace ConsoleApplication12
{
public class Node
{
public readonly int Data;
public Node Right, Left;
public Node(int key)
{
Data = key;
Right = Left = null;
}
}
public class BinaryTree
{
public Node Root;
public int FindMax(Node node)
{
if (node == null)
return int.MinValue;
var result = node.Data;
var leftResult = FindMax(node.Left);
var rightResult = FindMax(node.Right);
if (leftResult > result)
result = leftResult;
if (rightResult > result)
result = rightResult;
return result;
}
public int FindMin(Node node)
{
if (node == null)
return int.MaxValue;
var result = node.Data;
var leftResult = FindMax(node.Left);
var rightResult = FindMax(node.Right);
if (leftResult < result)
result = leftResult;
if (rightResult < result)
result = rightResult;
return result;
}
}
internal static class Program
{
public static void Main(string[] args)
{
var tree = new BinaryTree {Root = new Node(2) {Left = new Node(7), Right = new Node(5)}};
tree.Root.Left.Right = new Node(6) {Left = new Node(1), Right = new Node(11)};
tree.Root.Right.Right = new Node(9) {Left = new Node(4)};
Console.WriteLine("Maximum Number in Binary Tree : " + tree.FindMax(tree.Root));
Console.WriteLine("Minimum Number in Binary Tree : " + tree.FindMin(tree.Root));
}
}
}