-
Notifications
You must be signed in to change notification settings - Fork 1
/
treenode.h
106 lines (81 loc) · 2.09 KB
/
treenode.h
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
#ifndef TREENODE_H
#define TREENODE_H
#include <iostream>
using std::cout;
using std::cerr;
using std::endl;
using std::ostream;
#include <memory>
using std::unique_ptr;
#include <utility>
using std::pair;
template<class T>
class TreeNode {
public:
T data;
unique_ptr<TreeNode<T>> leftChild, rightChild;
TreeNode<T> *parent;
TreeNode(T d):data(d) {
this->parent = nullptr;
this->leftChild = nullptr;
this->rightChild = nullptr;
}
void setLeftChild(TreeNode<T> *child) {
this->leftChild.reset(child);
child->parent = this;
}
void setRightChild(TreeNode<T> *child) {
this->rightChild.reset(child);
child->parent = this;
}
void write(ostream &output) const {
if (this->leftChild != nullptr) {
this->leftChild->write(output);
}
output <<" " <<data<<" ";
if (this->rightChild != nullptr) {
this->rightChild->write(output);
}
}
class TreeNodeIterator {
TreeNode<T>* itr;
public:
TreeNodeIterator(TreeNode<T>* root) {
itr = root;
}
T& operator*() {
return itr->data;
}
bool operator==(TreeNode<T>::TreeNodeIterator temp) {
return itr == temp.itr;
}
bool operator!=(TreeNode<T>::TreeNodeIterator temp) {
return itr != temp.itr;
}
void operator++() {
if(itr->rightChild!=nullptr)
itr = (itr->rightChild).get();
else {
while(itr->parent!=NULL && (itr->parent->leftChild).get()!=itr)
itr = itr->parent;
if(itr!=NULL)
itr=itr->parent;
}
}
};
int maxDepth() {
return maxDepth(this);
}
private:
int maxDepth(TreeNode<T>* root) {
if (root == NULL)
return 0;
int a = maxDepth(root->leftChild.get());
int b = maxDepth(root->rightChild.get());
if (a > b)
return a + 1;
else
return b + 1;
}
};
#endif