-
Notifications
You must be signed in to change notification settings - Fork 0
/
TreeTraversal - DFS.cs
92 lines (77 loc) · 2.36 KB
/
TreeTraversal - DFS.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
87
88
89
90
91
92
/// <summary>
/// Depth First Traversals:
/// (a) Inorder (Left, Root, Right) : 4 2 5 1 3
/// (b) Preorder (Root, Left, Right) : 1 2 4 5 3
/// (c) Postorder (Left, Right, Root) : 4 5 2 3 1
/// </summary>
namespace Binary_Tree
{
class TreeTraversal
{
public class Node
{
public int key;
public Node? left, right;
public Node(int item)
{
key = item;
left = null;
right = null;
}
}
class BinaryTree
{
Node? root;
BinaryTree()
{
root = null;
}
// Left, Right, Root
void PostOrder(Node? root)
{
if (root == null)
return;
PostOrder(root.left);
PostOrder(root.right);
Console.Write(root.key + " ");
}
// Root, Left, Right
void PreOrder(Node? root)
{
if (root == null)
return;
Console.Write(root.key + " ");
PreOrder(root.left);
PreOrder(root.right);
}
// Left, Root, Right
void InOrder(Node? root)
{
if (root == null)
return;
InOrder(root.left);
Console.Write(root.key + " ");
InOrder(root.right);
}
void printPostorder() { PostOrder(root); }
void printPreorder() { PreOrder(root); }
void printInorder() { InOrder(root); }
public static void Main(String[] args)
{
BinaryTree tree = new BinaryTree();
tree.root = new Node(1);
tree.root.left = new Node(2);
tree.root.right = new Node(3);
tree.root.left.left = new Node(4);
tree.root.left.right = new Node(5);
Console.WriteLine("PostOrder traversal of binary tree is ");
tree.printPostorder();
Console.WriteLine("PreOrder traversal of binary tree is ");
tree.printPreorder();
Console.WriteLine("InOrder traversal of binary tree is ");
tree.printInorder();
}
}
}
}