# [LeetCode] 104. Maximum Depth of Binary Tree 二叉树的最大深度

2021年09月15日 阅读数：1

Given a binary tree, find its maximum depth.html

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

Note: A leaf is a node with no children.node

Example:python

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

```    3
/ \
9  20
/  \
15   7```

return its depth = 3.url

Java：DFSget

```public class Solution {
public int maxDepth(TreeNode root) {
return root == null ? 0 : (1 + Math.max(maxDepth(root.left), maxDepth(root.right)));
}
}
```

Java: Level Travesal

```public class Solution {
public int maxDepth(TreeNode root) {
if (root == null) return 0;
int res = 0;
q.offer(root);
while (!q.isEmpty()) {
++res;
int n = q.size();
for (int i = 0; i < n; ++i) {
TreeNode t = q.poll();
if (t.left != null) q.offer(t.left);
if (t.right != null) q.offer(t.right);
}
}
return res;
}
}
```

Python: DFS

```class Solution:
# @param root, a tree node
# @return an integer
def maxDepth(self, root):
if root is None:
return 0
else:
return max(self.maxDepth(root.left), self.maxDepth(root.right)) + 1
```

C++: DFS

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

C++:

```class Solution {
public:
int maxDepth(TreeNode* root) {
if (!root) return 0;
int res = 0;
queue<TreeNode*> q;
q.push(root);
while (!q.empty()) {
++res;
int n = q.size();
for (int i = 0; i < n; ++i) {
TreeNode *t = q.front(); q.pop();
if (t->left) q.push(t->left);
if (t->right) q.push(t->right);
}
}
return res;
}
};
```

[LeetCode] 366. Find Leaves of Binary Tree 找二叉树的叶节点

[LeetCode] 310. Minimum Height Trees 最小高度树

[LeetCode] 545. Boundary of Binary Tree 二叉树的边界