-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinary_tree.h
More file actions
94 lines (80 loc) · 2.29 KB
/
binary_tree.h
File metadata and controls
94 lines (80 loc) · 2.29 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
#ifndef CPP_ALGORITHM_BINARY_TREE_H
#define CPP_ALGORITHM_BINARY_TREE_H
namespace BinaryTree
{
/**
* \brief Binary tree node.
* \tparam T the type of the key
*/
template <typename T>
struct Node
{
T key;
Node* left;
Node* right;
Node()
: key{}, left{nullptr}, right{nullptr} {}
explicit Node(T key)
: key{key}, left{nullptr}, right{nullptr} {}
Node(T key, Node* left, Node* right)
: key{key}, left{left}, right{right} {}
};
/**
* \brief Extended binary tree node with parent pointer.
* \tparam T the type of the key
*/
template <typename T>
struct ExtendedNode
{
T key;
ExtendedNode* parent;
ExtendedNode* left;
ExtendedNode* right;
ExtendedNode()
: key{}, parent{nullptr}, left{nullptr}, right{nullptr} {}
explicit ExtendedNode(T key)
: key{key}, parent{nullptr}, left{nullptr}, right{nullptr} {}
ExtendedNode(T key, ExtendedNode* parent, ExtendedNode* left, ExtendedNode* right)
: key{key}, parent{parent}, left{left}, right{right}
{
}
};
/**
* \brief Extended binary tree node with next pointer.
* \tparam T the type of the key
*/
template <typename T>
struct NextExtendedNode
{
T key;
NextExtendedNode* left;
NextExtendedNode* right;
NextExtendedNode* next;
NextExtendedNode()
: key{}, left{nullptr}, right{nullptr}, next{nullptr} {}
explicit NextExtendedNode(T key)
: key{key}, left{nullptr}, right{nullptr}, next{nullptr} {}
NextExtendedNode(T key, NextExtendedNode* left, NextExtendedNode* right, NextExtendedNode* next)
: key{key}, left{left}, right{right}, next{nullptr}
{
}
};
/**
* \brief Get the height of a binary tree.
* \tparam T the type of the key
* \param node the root of the tree
* \return the height of the tree
*/
template <typename T>
auto ExtendedNodeTreeDepth(const ExtendedNode<T>* node) -> int
{
auto depth = 0;
while (node->parent)
{
++depth;
node = node->parent;
}
return depth;
}
}
#endif