-
Notifications
You must be signed in to change notification settings - Fork 0
/
BinaryTreeInt.cs
106 lines (94 loc) · 2.63 KB
/
BinaryTreeInt.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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Exercise2
{
public class BinaryTreeInt
{
private NodeInt root;
public BinaryTreeInt()
{
root = null;
}
public void Insert(int data)
{
root = Insert(root, data);
}
private NodeInt Insert(NodeInt node, int data)
{
if (node == null)
{
node = new NodeInt(data);
}
else
{
if (data < node.Data)
{
node.Left = Insert(node.Left, data);
}
else if (data > node.Data)
{
node.Right = Insert(node.Right, data);
}
}
return node;
}
public List<int> PreOrder()
{
List<int> result = new List<int>();
PreOrderTraversal(root, result);
return result;
}
private void PreOrderTraversal(NodeInt node, List<int> result)
{
if (node != null)
{
result.Add(node.Data);
PreOrderTraversal(node.Left, result);
PreOrderTraversal(node.Right, result);
}
}
public List<int> InOrder()
{
List<int> result = new List<int>();
InOrderTraversal(root, result);
return result;
}
private void InOrderTraversal(NodeInt node, List<int> result)
{
if (node != null)
{
InOrderTraversal(node.Left, result);
result.Add(node.Data);
InOrderTraversal(node.Right, result);
}
}
public List<int> PostOrder()
{
List<int> result = new List<int>();
PostOrderTraversal(root, result);
return result;
}
private void PostOrderTraversal(NodeInt node, List<int> result)
{
if (node != null)
{
PostOrderTraversal(node.Left, result);
PostOrderTraversal(node.Right, result);
result.Add(node.Data);
}
}
public int Count()
{
return Count(root);
}
private int Count(NodeInt node)
{
if (node == null)
return 0;
return 1 + Count(node.Left) + Count(node.Right);
}
}
}