-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathleetcode104_max_depth_of_binary_tree.cpp
74 lines (63 loc) · 1.66 KB
/
leetcode104_max_depth_of_binary_tree.cpp
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
/**
* @file leetcode104_max_depth_of_binary_tree.cpp
* @author wangguibao(https://github.com/wangguibao)
* @date 2023/06/07 19:35
* @brief https://leetcode.com/problems/maximum-depth-of-binary-tree
*
**/
#include <iostream>
#include <vector>
#include <string>
#include <queue>
/**
* Definition for a binary tree node.
*/
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode() : val(0), left(nullptr), right(nullptr) {}
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};
class Solution {
public:
int maxDepth(TreeNode* root) {
if (!root) {
return 0;
}
return std::max(maxDepth(root->left), maxDepth(root->right)) + 1;
}
};
TreeNode* construct_tree() {
TreeNode* root = new TreeNode(5);
root->left = new TreeNode(1);
root->right = new TreeNode(4);
auto right = root->right;
right->left = new TreeNode(3);
right->right = new TreeNode(6);
return root;
}
void print_tree(TreeNode* root) {
std::queue<TreeNode*> q;
q.push(root);
while (!q.empty()) {
TreeNode* node = q.front();
q.pop();
std::cout << node->val << " ";
if (node->left) {
q.push(node->left);
}
if (node->right) {
q.push(node->right);
}
}
std::cout << std::endl;
}
int main() {
TreeNode* root = construct_tree();
Solution solution;
auto ret = solution.maxDepth(root);
std::cout << ret << std::endl;
return 0;
}