-
Notifications
You must be signed in to change notification settings - Fork 0
/
BinaryTree.CS
86 lines (71 loc) · 1.77 KB
/
BinaryTree.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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
using System;
namespace ConsoleApplication11
{
public class Node
{
public readonly int Key;
public Node Left;
public Node Right;
public Node(int item)
{
Key = item;
Left = Right = null;
}
}
public class BinaryTree
{
public Node Root;
public BinaryTree()
{
Root = null;
}
private static void InOrder(Node node)
{
while (true)
{
if (node == null) return;
InOrder(node.Left);
Console.WriteLine(node.Key + " ");
node = node.Right;
}
}
private static void PreOrder(Node node)
{
while (true)
{
if (node == null) return;
Console.WriteLine(node.Key + " ");
PreOrder(node.Left);
node = node.Right;
}
}
private static void PostOrder(Node node)
{
if(node == null) return;
PostOrder(node.Left);
PostOrder(node.Right);
Console.WriteLine(node.Key + " ");
}
public void InOrder(){InOrder(Root);}
public void PreOrder(){PreOrder(Root);}
public void PostOrder(){PostOrder(Root);}
}
internal static class Program
{
public static void Main()
{
var binaryTree = new BinaryTree {Root = new Node(1) {Left = new Node(2), Right = new Node(3)}};
binaryTree.Root.Left.Left = new Node(4);
binaryTree.Root.Left.Right = new Node(5);
Console.WriteLine("PreOrder traversal " +
"of binary tree is ");
binaryTree.PreOrder();
Console.WriteLine("\nInOrder traversal " +
"of binary tree is ");
binaryTree.InOrder();
Console.WriteLine("\nPostOrder traversal " +
"of binary tree is ");
binaryTree.PostOrder();
}
}
}