-
Notifications
You must be signed in to change notification settings - Fork 55
Expand file tree
/
Copy pathTree.cs
More file actions
130 lines (127 loc) · 3.97 KB
/
Tree.cs
File metadata and controls
130 lines (127 loc) · 3.97 KB
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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
using System;
namespace SQLBench
{
//Create a Node class
class Node
{
public Node LeftNode;
public Node RightNode;
public long Data;
public void DisplayNode()
{
//output for console application to display all the nodes
Console.Write(Data + " ");
}
}
class Tree
{
//Crreate root node
public Node root;
public Tree()
{
root = null;
}
~Tree()
{
}
public Node ReturnRoot()
{
return root;
}
public void AddNode(long mydata)
{
//create a new node
Node newNode = new Node();
//assign Data in node to a long integer
newNode.Data = mydata;
//check root for null value
//if root is null assign newNode to root else
//assign a parent node and check left and right children
if (root == null)
root = newNode;
else
{
Node current = root;
Node parent;
while (true)
{
parent = current;
if (mydata < current.Data)
{
current = current.LeftNode;
if (current == null)
{
parent.LeftNode = newNode;
break;
}
}
else
{
current = current.RightNode;
if (current == null)
{
parent.RightNode = newNode;
break;
}
}
}
}
}
public void Preorder(Node Root)
{
//reorder sort for tree
if (Root != null)
{
// Console.Write(Root.Data + " ");
Preorder(Root.LeftNode);
Preorder(Root.RightNode);
}
}
public void Inorder(Node Root)
{
//in order sort for nodes
if (Root != null)
{
Inorder(Root.LeftNode);
//Console.Write(Root.Data + " ");
Inorder(Root.RightNode);
}
}
public void Postorder(Node Root)
{
//post order sort
if (Root != null)
{
Postorder(Root.LeftNode);
Postorder(Root.RightNode);
// Console.Write(Root.Data + " ");
}
}
public Node findNode(int index, Node Root)
{
//find the node if the root is not null
if (Root != null)
{
if (index == Root.Data)
return Root;
if (index < Root.Data)
return findNode(index, Root.LeftNode);
else
return findNode(index, Root.RightNode);
}
return null;
}
public int GetTreeDepth()
{
//return tree depth
return this.GetTreeDepth(this.root);
}
private int GetTreeDepth(Node Root)
{
//get tree depth
return Root == null ? 0 : Math.Max(GetTreeDepth(Root.LeftNode), GetTreeDepth(Root.RightNode)) + 1;
}
}
}