-
Notifications
You must be signed in to change notification settings - Fork 0
/
TreeNode.h
93 lines (73 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
//
// Created by abasiy on ۲۱/۱۱/۲۰۲۳.
//
#include "LinkList.h"
#ifndef DATASTRUCTURE_TREENODE_H
#define DATASTRUCTURE_TREENODE_H
template <class T>
class TreeNode {
private:
TreeNode<T>* parent;
LinkList<TreeNode<T>*> children;
T value;
public:
TreeNode(T value, TreeNode<T> *parent = nullptr){
this->parent = parent;
this->children = LinkList<TreeNode<T>*>();
this->value = value;
}
~TreeNode(){
for (auto it = this->children.begin() ; it != nullptr ; it = it->nextNode()) {
delete it;
}
};
TreeNode<T>* popLeftChild(){
return children.popFront();
}
bool isLeaf(){
return children.isEmpty();
}
void setChildren(LinkList<TreeNode<T> *> list_of_children){
delete this->children;
this->children = list_of_children;
}
void pushChildRight(TreeNode<T> *child_ptr){
this->children.pushEnd(child_ptr);
}
void pushChildRight(T data){
this->children.pushEnd(new TreeNode<T>(data, this));
}
void pushChildLeft(TreeNode<T> *child_ptr){
this->children.pushFront(child_ptr);
}
void pushChildLeft(T data){
this->children.pushFront(new TreeNode<T>(data, this));
}
LinkList<TreeNode<T> *> getChildren() const {
return children;
}
TreeNode<T> *getParent() const {
return parent;
}
TreeNode<T> *popNextSibling(){
if (!this->parent->children.isEmpty()) {
return this->parent->children.popFront();
} else {
return nullptr;
}
}
TreeNode<T> *nextSibling(){
if (this->parent == nullptr) return nullptr;
LinkList<TreeNode<T> *> sibling = this->parent->getChildren();
int index_in_sibling = sibling.find(this);
if (index_in_sibling == -1 || index_in_sibling + 1 == sibling.length()) return nullptr;
return sibling.getAt(index_in_sibling + 1);
}
void setValue(T new_value){
this->value = new_value;
}
T getValue(){
return this->value;
}
};
#endif //DATASTRUCTURE_TREENODE_H