-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtree.cpp
More file actions
36 lines (33 loc) · 909 Bytes
/
Copy pathtree.cpp
File metadata and controls
36 lines (33 loc) · 909 Bytes
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
#include "tree.h"
#include <stack>
BinaryTree::BinaryTree(std::vector<int> &val_list) {
if (val_list.size() == 0) {
this->root = nullptr;
return;
}
std::stack<TreeNode **> my_stack;
my_stack.push(&this->root);
TreeNode **ptr;
for (int val : val_list) {
ptr = my_stack.top();
my_stack.pop();
if (val != -1) {
*ptr = new TreeNode(val);
my_stack.push(&((*ptr)->right));
my_stack.push(&((*ptr)->left));
}
}
}
BinaryTree::~BinaryTree() {
if (this->root == nullptr) return;
std::stack<TreeNode *> my_stack;
my_stack.push(this->root);
TreeNode *ptr;
while (!my_stack.empty()) {
ptr = my_stack.top();
my_stack.pop();
if (ptr->left != nullptr) my_stack.push(ptr->left);
if (ptr->right != nullptr) my_stack.push(ptr->right);
delete ptr;
}
}