Merge pull request #102 from Joshua-Lu/patch-19

添加 0104.二叉树的最大深度 Java版本 递归法与迭代法
This commit is contained in:
Carl Sun
2021-05-14 10:29:32 +08:00
committed by GitHub

View File

@ -231,19 +231,53 @@ public:
Java
```java
```Java
class Solution {
/**
* 递归法
*/
public int maxDepth(TreeNode root) {
if (root == null) {
return 0;
}
int leftdeep = maxDepth(root.left);
int rightdeep = maxDepth(root.right);
return 1+Math.max(leftdeep,rightdeep);
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