-
Notifications
You must be signed in to change notification settings - Fork 0
/
104.二叉树的最大深度.java
44 lines (42 loc) · 1.14 KB
/
104.二叉树的最大深度.java
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
/*
* @lc app=leetcode.cn id=104 lang=java
*
* [104] 二叉树的最大深度
*/
// @lc code=start
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int maxDepth(TreeNode root) {
if (root == null) {return 0;}
Queue<TreeNode> queue = new LinkedList<TreeNode>();
Set<TreeNode> set = new HashSet();
int depth = 0;
queue.add(root);
while (!queue.isEmpty()) {
TreeNode currNode = queue.poll();
set.add(currNode);
if (queue.isEmpty() && set.size() > 0) {
depth++;
set.forEach((tmpNode) -> {
if (tmpNode.left != null) {
((LinkedList<TreeNode>) queue).add(tmpNode.left);
}
if (tmpNode.right != null) {
((LinkedList<TreeNode>) queue).add(tmpNode.right);
}
});
set.clear();
}
}
return depth;
}
}
// @lc code=end