-
Notifications
You must be signed in to change notification settings - Fork 26
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Leetcode 104 Maximum Depth of Binary Tree
- Loading branch information
1 parent
3e7950b
commit 62158bc
Showing
1 changed file
with
21 additions
and
0 deletions.
There are no files selected for viewing
21 changes: 21 additions & 0 deletions
21
0104_Maximum Depth of Binary Tree/MaximumDepthofBinaryTree4.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,21 @@ | ||
class Solution { | ||
public int maxDepth(TreeNode root) { | ||
if(root == null) return 0; | ||
int ans = 1; | ||
Queue<Pair<TreeNode,Integer>> q = new LinkedList<>(); | ||
q.offer(new Pair<TreeNode,Integer>(root, 1)); | ||
while(q.size() > 0) { | ||
Pair<TreeNode, Integer> pair = q.poll(); | ||
TreeNode node = pair.getKey(); | ||
int depth = pair.getValue(); | ||
ans = Math.max(ans, depth); | ||
if(node.left != null) | ||
q.offer(new Pair<TreeNode, Integer>(node.left, depth+1)); | ||
|
||
if(node.right != null) | ||
q.offer(new Pair<TreeNode, Integer>(node.right, depth+1)); | ||
} | ||
|
||
return ans; | ||
} | ||
} |