mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 19:44:45 +08:00
Update 0104.二叉树的最大深度.md
添加 0104.二叉树的最大深度 Java版本
This commit is contained in:
@ -231,7 +231,51 @@ public:
|
|||||||
|
|
||||||
|
|
||||||
Java:
|
Java:
|
||||||
|
```Java
|
||||||
|
class Solution {
|
||||||
|
/**
|
||||||
|
* 递归法
|
||||||
|
*/
|
||||||
|
public int maxDepth(TreeNode root) {
|
||||||
|
if (root == null) {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
int leftDepth = maxDepth(root.left);
|
||||||
|
int rightDepth = maxDepth(root.right);
|
||||||
|
return Math.max(leftDepth, rightDepth) + 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
```Java
|
||||||
|
class Solution {
|
||||||
|
/**
|
||||||
|
* 迭代法,使用层序遍历
|
||||||
|
*/
|
||||||
|
public int maxDepth(TreeNode root) {
|
||||||
|
if(root == null) {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
Deque<TreeNode> deque = new LinkedList<>();
|
||||||
|
deque.offer(root);
|
||||||
|
int depth = 0;
|
||||||
|
while (!deque.isEmpty()) {
|
||||||
|
int size = deque.size();
|
||||||
|
depth++;
|
||||||
|
for (int i = 0; i < size; i++) {
|
||||||
|
TreeNode poll = deque.poll();
|
||||||
|
if (poll.left != null) {
|
||||||
|
deque.offer(poll.left);
|
||||||
|
}
|
||||||
|
if (poll.right != null) {
|
||||||
|
deque.offer(poll.right);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return depth;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
Python:
|
Python:
|
||||||
|
|
||||||
|
Reference in New Issue
Block a user