-
Notifications
You must be signed in to change notification settings - Fork 0
/
Tree
107 lines (91 loc) · 2.57 KB
/
Tree
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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
using System;
using System.Collections.Generic;
using System.Text;
namespace Test
{
public class TNode
{
public TNode Left;
public TNode Right;
public int data;
}
public class Tree
{
public TNode Root;
public void PreOrder(TNode node)
{
if (node == null)
return;
/* first print data of node */
Console.Write(node.data + " ");
/* then recur on left sutree */
PreOrder(node.Left);
/* now recur on right subtree */
PreOrder(node.Right);
}
public void InOrder(TNode node)
{
if (node == null)
return;
/* first recur on left child */
InOrder(node.Left);
/* then print the data of node */
Console.Write(node.data + " ");
/* now recur on right child */
InOrder(node.Right);
}
public void PostOrder(TNode node)
{
if (node == null)
return;
// first recur on left subtree
PostOrder(node.Left);
// then recur on right subtree
PostOrder(node.Right);
// now deal with the node
Console.Write(node.data + " ");
}
public void AddNode(int item)
{
if (Root == null)
{
this.Root = new TNode();
this.Root.data = item;
}
else
{
var a = Root.data;
TNode curr = Root;
while (a != 0)
{
if (curr.data > item)
{
if (curr.Left == null)
{
curr.Left = new TNode();
curr.Left.data = item;
a = 0;
}
else
{
curr = curr.Left;
}
}
if (curr.data < item)
{
if (curr.Right == null)
{
curr.Right = new TNode();
curr.Right.data = item;
a = 0;
}
else
{
curr = curr.Right;
}
}
}
}
}
}
}