104. maximum depth of binary tree

Given a binary tree, find its maximum depth.

The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

1. 深度遍历

1
2
3
4
5
6
7
8
class Solution {
public:
int (TreeNode* root) {
if (root == NULL)
return 0;
return max(maxDepth(root->left),maxDepth(root->right)) + 1;
}
};

2. 广度遍历

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
class Solution {
public:
int (TreeNode *root)
{

if (root == NULL)
return 0;

queue<TreeNode *> p;
p.push(root);
int depth = 0;
while (!p.empty())
{
depth++;
int count = p.size();
for (int i = 0; i < count; i++)
{
TreeNode *tmp = p.front();
if (tmp->left != NULL)
p.push(tmp->left);

if (tmp->right != NULL)
p.push(tmp->right);
p.pop();
}

}
return depth;
}
};