forked from HelloLondon/BinaryTree-1
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBinaryTree.cpp
103 lines (88 loc) · 1.65 KB
/
BinaryTree.cpp
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
#include "BinaryTree.h"
#include <iostream>
using std::cout;
using std::endl;
BinaryTree::BinaryTree()
{
rootNode = NULL;
}
BinaryTree::~BinaryTree()
{
if(rootNode == NULL)
return; // Nothing to do
removeSubtree(rootNode);
}
void BinaryTree::removeSubtree(BinaryTreeNode* x)
{
if(x == NULL)
return; // Nothing to do
BinaryTreeNode* left = x->leftNode;
BinaryTreeNode* right = x->rightNode;
delete x;
removeSubtree(left);
removeSubtree(right);
}
void BinaryTree::postorderTreeWalk(BinaryTreeNode* x)
{
if(x != NULL)
{
inorderTreeWalk(x->leftNode);
inorderTreeWalk(x->rightNode);
cout << "Node key: " << x->nodeKey << endl;
}
}
void BinaryTree::inorderTreeWalk(BinaryTreeNode* x)
{
if(x != NULL)
{
inorderTreeWalk(x->leftNode);
cout << "Node key: " << x->nodeKey << endl;
inorderTreeWalk(x->rightNode);
}
}
void BinaryTree::preorderTreeWalk(BinaryTreeNode* x)
{
if(x != NULL)
{
cout << "Node key: " << x->nodeKey << endl;
inorderTreeWalk(x->leftNode);
inorderTreeWalk(x->rightNode);
}
}
void BinaryTree::treeInsert(BinaryTreeNode* node)
{
BinaryTreeNode* y = NULL;
BinaryTreeNode* x = rootNode;
while(x != NULL)
{
y = x;
if(node->nodeKey < x->nodeKey)
x = x->leftNode;
else
x = x->rightNode;
}
node->parentNode = y;
if(y == NULL)
{
rootNode = node; // tree was empty
} else if (node->nodeKey < y->nodeKey)
{
y->leftNode = node;
} else
{
y->rightNode = node;
}
}
BinaryTreeNode* BinaryTree::treeSearch(double k)
{
BinaryTreeNode* x = rootNode;
if(x == NULL) return NULL;
while(x != NULL && x->nodeKey != k)
{
if (k < x->nodeKey)
x = x->leftNode;
else
x = x->rightNode;
}
return x;
}