Update 二叉树相关.md

master
Omooo 4 years ago
parent 84be72e5fd
commit 842de9d702
  1. 42
      blogs/Algorithm/剑指 Offer/二叉树相关.md

@ -194,3 +194,45 @@ class Solution {
}
```
#### [55 - I. 二叉树的深度](https://leetcode-cn.com/problems/er-cha-shu-de-shen-du-lcof/)
```java
class Solution {
public int maxDepth(TreeNode root) {
if (root == null) {
return 0;
}
return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;
}
}
```
```java
class Solution {
public int maxDepth(TreeNode root) {
if (root == null) {
return 0;
}
int result = 0;
Deque<TreeNode> queue = new LinkedList<>();
queue.add(root);
while (!queue.isEmpty()) {
result++;
int n = queue.size();
for (int i = 0; i < n; i++) {
TreeNode node = queue.poll();
if (node.left != null) {
queue.add(node.left);
}
if (node.right != null) {
queue.add(node.right);
}
}
}
return result;
}
}
```

Loading…
Cancel
Save