-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path104_max_depth.cpp
More file actions
51 lines (41 loc) · 1.42 KB
/
Copy path104_max_depth.cpp
File metadata and controls
51 lines (41 loc) · 1.42 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
#include <algorithm>
#include <iostream>
#include <memory>
#include <string>
#include <queue>
#include "parse_input.h"
class Solution {
public:
// DFS: O(N) time, O(logN) space
int maxDepth_DFS(const std::shared_ptr<TreeNode>& root) {
if (!root)
return 0;
return 1 + std::max(maxDepth_DFS(root->left), maxDepth_DFS(root->right));
}
// BFS: O(N) time, O(N) space
int maxDepth_BFS(const std::shared_ptr<TreeNode>& root) {
std::queue<const std::shared_ptr<TreeNode>> layer;
if (root) layer.push(root);
int count = 0;
while(!layer.empty()){
int layer_size = layer.size();
for (int i = 0; i < layer_size; i++){
const std::shared_ptr<TreeNode> cur_node = layer.front();
layer.pop();
if(cur_node->left) layer.push(cur_node->left);
if(cur_node->right) layer.push(cur_node->right);
}
count++;
}
return count;
}
};
int main(){
std::cout << "A tree represented by a space separated list (null for a missing node): ";
std::string line;
std::getline(std::cin, line);
std::shared_ptr<TreeNode> root = string2tree(line);
std::cout << "Maximum depth (by DFS): " << Solution().maxDepth_DFS(root) << std::endl;
std::cout << "Maximum depth (by BFS): " << Solution().maxDepth_BFS(root) << std::endl;
return 0;
}