-
Notifications
You must be signed in to change notification settings - Fork 0
/
tree.hpp
61 lines (51 loc) · 1.49 KB
/
tree.hpp
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
//
// Created by Tomáš Petříček on 11.07.2023.
//
#ifndef LEET_CODE_TREE_HPP
#define LEET_CODE_TREE_HPP
#include <vector>
#include <queue>
namespace tree {
struct node {
int val;
node* left;
node* right;
node()
:val(0), left(nullptr), right(nullptr) { }
explicit node(int x)
:val(x), left(nullptr), right(nullptr) { }
node(int x, node* left, node* right)
:val(x), left(left), right(right) { }
};
static constexpr int empty = -1;
static node* build(const std::vector<int>& vals)
{
if (vals.empty()) return nullptr;
auto* tree = new node{vals[0]};
std::queue<node*> parents;
parents.push(tree);
std::size_t i{1};
while (!parents.empty() && i<vals.size()) {
node* parent = parents.front();
parents.pop();
if (vals[i]!=empty && i<vals.size()) {
parent->left = new node{vals[i]};
parents.push(parent->left);
}
i++;
if (vals[i]!=empty && i<vals.size()) {
parent->right = new node{vals[i]};
parents.push(parent->right);
}
i++;
}
return tree;
}
bool same(tree::node* p, tree::node* q) {
if (!p || !q) {
return p==q;
}
return (p->val == q->val) && same(p->right, q->right) && same(p->left, q->left);
}
}
#endif //LEET_CODE_TREE_HPP