-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathLeetCode-104-Maximum-Depth-of-Binary-Tree.java
More file actions
45 lines (39 loc) · 1.22 KB
/
LeetCode-104-Maximum-Depth-of-Binary-Tree.java
File metadata and controls
45 lines (39 loc) · 1.22 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
/*
LeetCode: https://leetcode.com/problems/maximum-depth-of-binary-tree/
LintCode: http://www.lintcode.com/problem/maximum-depth-of-binary-tree/
JiuZhang: http://www.jiuzhang.com/solutions/maximum-depth-of-binary-tree/
ProgramCreek:
*/
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
// 1.DFS
// public int maxDepth(TreeNode root) {
// if(root == null) return 0;
// return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;
// }
// 2.BFS (level order traversal - Queue)
public int maxDepth(TreeNode root) {
if(root == null) return 0;
Queue<TreeNode> queue = new LinkedList<TreeNode>();
queue.offer(root);
int depth = 0;
while(!queue.isEmpty()){
depth++;
int size = queue.size();
for(int i = 0; i < size; i++){
TreeNode curr = queue.poll();
if(curr.left != null) queue.offer(curr.left);
if(curr.right != null) queue.offer(curr.right);
}
}
return depth;
}
}