-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtree.cpp
More file actions
81 lines (73 loc) · 2.2 KB
/
tree.cpp
File metadata and controls
81 lines (73 loc) · 2.2 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
#include <vector>
#include <queue>
#include <iostream>
#include <string>
#include <sstream>
#include <algorithm>
#include <cmath>
using namespace std;
// Definition for a binary tree node.
template<typename T>
struct TreeNode {
T val;
TreeNode<T>* left;
TreeNode<T>* right;
TreeNode() : val(0), left(nullptr), right(nullptr) {}
TreeNode(T x) : val(x), left(nullptr), right(nullptr) {}
TreeNode(T x, TreeNode<T>* left, TreeNode<T>* right) : val(x), left(left), right(right) {}
};
template<typename T>
class Solution {
public:
TreeNode<T>* createTree(vector<string>& nodes) {
if (nodes.empty()) return nullptr;
if (nodes[0] == "null") return nullptr;
TreeNode<T>* root = new TreeNode<T>(stoi(nodes[0]));
queue<TreeNode<T>*> q;
q.push(root);
int i = 1;
while (!q.empty() && i < nodes.size()) {
TreeNode<T>* curr = q.front();
q.pop();
if (i < nodes.size() && nodes[i] != "null") {
curr->left = new TreeNode<T>(stoi(nodes[i]));
q.push(curr->left);
}
++i;
if (i < nodes.size() && nodes[i] != "null") {
curr->right = new TreeNode<T>(stoi(nodes[i]));
q.push(curr->right);
}
++i;
}
return root;
}
TreeNode<T>* createTreeFromLevelOrder(vector<T>& nums) {
vector<string> nodes;
for (T num : nums) {
nodes.push_back(num == numeric_limits<T>::min() ? "null" : to_string(num));
}
return createTree(nodes);
}
};
int main() {
Solution<int> solution;
vector<int> nums = {1, 2, numeric_limits<int>::min(), 3, numeric_limits<int>::min(), 4, numeric_limits<int>::min(), 5};
TreeNode<int>* root = solution.createTreeFromLevelOrder(nums);
// 测试代码,遍历二叉树,打印结果
queue<TreeNode<int>*> q;
q.push(root);
while (!q.empty()) {
TreeNode<int>* curr = q.front();
q.pop();
if (curr) {
cout << curr->val << " ";
q.push(curr->left);
q.push(curr->right);
} else {
cout << "null ";
}
}
cout << endl;
return 0;
}