-
Notifications
You must be signed in to change notification settings - Fork 1.9k
/
tree_level_order.cc
48 lines (41 loc) · 1.26 KB
/
tree_level_order.cc
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
#include <memory>
#include <queue>
#include <vector>
#include "binary_tree_node.h"
#include "test_framework/generic_test.h"
using std::queue;
using std::unique_ptr;
using std::vector;
vector<vector<int>> BinaryTreeDepthOrder(
const unique_ptr<BinaryTreeNode<int>>& tree) {
vector<vector<int>> result;
if (!tree.get()) {
return result;
}
queue<BinaryTreeNode<int>*> curr_depth_nodes({tree.get()});
while (!empty(curr_depth_nodes)) {
queue<BinaryTreeNode<int>*> next_depth_nodes;
vector<int> this_level;
while (!empty(curr_depth_nodes)) {
auto curr = curr_depth_nodes.front();
curr_depth_nodes.pop();
this_level.emplace_back(curr->data);
if (curr->left) {
next_depth_nodes.emplace(curr->left.get());
}
if (curr->right) {
next_depth_nodes.emplace(curr->right.get());
}
}
result.emplace_back(this_level);
curr_depth_nodes = next_depth_nodes;
}
return result;
}
int main(int argc, char* argv[]) {
std::vector<std::string> args{argv + 1, argv + argc};
std::vector<std::string> param_names{"tree"};
return GenericTestMain(args, "tree_level_order.cc", "tree_level_order.tsv",
&BinaryTreeDepthOrder, DefaultComparator{},
param_names);
}