-
Notifications
You must be signed in to change notification settings - Fork 2
/
extras.cpp
executable file
·115 lines (93 loc) · 2.29 KB
/
extras.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
104
105
106
107
108
109
110
111
112
113
114
115
// height()
template <typename T>
int BinaryTree<T>::height() const
{
return height(root);
}
// height() recursive helper function
template <typename T>
int BinaryTree<T>::height(const Node * subRoot) const
{
if (subRoot == NULL) return -1;
return 1 + max(height(subRoot->left), height(subRoot->right));
}
// mirror()
template <typename T>
void BinaryTree<T>::mirror()
{
mirror(root);
}
// mirror() recursive helper
template <typename T>
typename BinaryTree<T>::Node * BinaryTree<T>::mirror(Node * subRoot)
{
if (subRoot == NULL) return NULL;
// Swap and mirror
Node * temp = subRoot->left;
subRoot->left = mirror(subRoot->right);
subRoot->right = mirror(temp);
return subRoot;
}
// isOrdered()
template <typename T>
bool BinaryTree<T>::isOrdered() const
{
return isOrdered(root);
}
// isOrdered() recursive helper
template <typename T>
bool BinaryTree<T>::isOrdered(const Node * subRoot) const
{
if (subRoot == NULL) return true;
return isOrdered(subRoot->left) && isOrdered(subRoot->right) &&
(subRoot->left == NULL || rightMost(subRoot->left)->elem <= subRoot->elem) &&
(subRoot->right == NULL || leftMost(subRoot->right)->elem >= subRoot->elem) ;
}
// Find the left-most child of a node
template <typename T>
const typename BinaryTree<T>::Node * BinaryTree<T>::leftMost(const Node * subRoot) const
{
while (subRoot->left != NULL)
subRoot = subRoot->left;
return subRoot;
}
// Find the right-most child of a node
template <typename T>
const typename BinaryTree<T>::Node * BinaryTree<T>::rightMost(const Node * subRoot) const
{
while (subRoot->right != NULL)
subRoot = subRoot->right;
return subRoot;
}
// printPathSums()
template <typename T>
void BinaryTree<T>::printPaths() const
{
if (root == NULL)
{
cout << "(no paths)" << endl;
return;
}
vector<T> path;
printPaths(root, path);
}
// printPathSums recursive helper function
template <typename T>
void BinaryTree<T>::printPaths(const Node * node, vector<T> & path) const
{
if (node == NULL) return;
path.push_back(node->elem);
if (node->left == NULL && node->right == NULL)
{
cout << "Path:";
for (size_t i = 0; i < path.size(); i++)
cout << ' ' << path[i];
cout << endl;
}
else
{
printPaths(node->left, path);
printPaths(node->right, path);
}
path.pop_back();
}