-
Notifications
You must be signed in to change notification settings - Fork 13
/
LC_109_MaximalDepthOfBinaryTree.cpp
73 lines (66 loc) · 1.79 KB
/
LC_109_MaximalDepthOfBinaryTree.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
#include <bits/stdc++.h>
using namespace std;
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:
// // recursive approach
// int maxDepth(TreeNode *root)
// {
// // base case
// if (root == NULL)
// {
// return 0;
// }
// int leftHeight = maxDepth(root->left);
// int rightHeight = maxDepth(root->right);
// int height = max(leftHeight, rightHeight) + 1; // +1 for root node
// return height;
// }
// using level order traversal
int maxDepth(TreeNode *root)
{
// dfs
// if(!root) return 0;
// int leftHeight = maxDepth(root->left);
// int rightHeight = maxDepth(root->right);
// return max(leftHeight, rightHeight) + 1;
// bfs
if(!root) return 0;
queue<TreeNode*> q;
q.push(root);
int c = 0;
while (!q.empty()) {
int s = q.size();
c++;
for (int i = 0; i < s; i++) {
TreeNode* node = q.front();
q.pop();
if (node->left != NULL)
q.push(node->left);
if (node->right != NULL)
q.push(node->right);
}
}
return c;
}
};
int main()
{
Solution obj;
TreeNode *root = new TreeNode(3);
root->left = new TreeNode(9);
root->right = new TreeNode(20);
// root->right->left = new TreeNode(15);
// root->right->right = new TreeNode(7);
cout << obj.maxDepth(root) << endl;
return 0;
}