# LeetCode104. Maximum Depth of Binary Tree（二叉树 / 搜索）

## LeetCode104. Maximum Depth of Binary Tree（二叉树 / 搜索）

• Easy
• Accepted：458,799
• Submissions：774,287

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.

Note: A leaf is a node with no children.

Example:

Given binary tree [3,9,20,null,null,15,7],

3
/ \
9  20
/  \
15   7

return its depth = 3.

### 链接

https://leetcode.com/problems/maximum-depth-of-binary

### 代码

• Runtime: 16 ms, faster than 99.26% of C++ online submissions for Maximum Depth of Binary Tree.
• Memory Usage: 19.6 MB, less than 12.18% of C++ online submissions for Maximum Depth of Binary Tree.
/**
* Definition for a binary tree node.
* struct TreeNode {
*     int val;
*     TreeNode *left;
*     TreeNode *right;
*     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/

class Solution {
public:
int maxDepth(TreeNode* root) {
if (root == NULL)
return 0;
int leftMaxDepth = maxDepth(root->left);
int rightMaxDepth = maxDepth(root->right);
return max(leftMaxDepth, rightMaxDepth) + 1;
}
};

// simple
class Solution {
public:
int maxDepth(TreeNode* root) {
return root == NULL ? 0 : max(maxDepth(root->left), maxDepth(root->right)) + 1;
}
};
• 当然我们也可以使用队列，即bfs。
class Solution {
public:
int maxDepth(TreeNode* root) {
if (root == NULL)
return 0;
int ans = 0;
queue <TreeNode*> q;
q.push(root);
while (!q.empty())
{
++ans;
int n = q.size();
for (int i = 0; i < n; ++i)
{
TreeNode* p = q.front();
q.pop();
if (p->left != NULL)
q.push(p->left);
if (p->right != NULL)
q.push(p->right);
}
}
return ans;
}
};

### 参考

https://leetcode.com/problems/maximum-depth-of-binary-tree/discuss/34207

The end.
2019年3月7日 星期四