forked from terrytong0876/LintCode-1
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path104. Maximum Depth of Binary Tree.java
More file actions
executable file
·61 lines (48 loc) · 1.18 KB
/
Copy path104. Maximum Depth of Binary Tree.java
File metadata and controls
executable file
·61 lines (48 loc) · 1.18 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
E
tags: DFS, Tree
给一个binary tree, 找最深depth
#### DFS
- 这里要走过所有的node, 所以dfs非常合适
- Divide and conquer.
- 维持一个最大值: Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;
- 注意check root == null
#### Note
- BFS is doable as well, but a bit more code to write: tracks largest level we reach
```
/*
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.
*/
/*
Thinking process:
check if root is null, return 0 if so.
Divide and return integer as the depth
Conquer: find the max and return depth + 1.
*/
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public int maxDepth(TreeNode root) {
if (root == null) {
return 0;
}
return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;
}
}
```