Skip to content

Commit

Permalink
Leetcode 104 Maximum Depth of Binary Tree
Browse files Browse the repository at this point in the history
  • Loading branch information
jiajionline committed Jun 13, 2021
1 parent e050dd2 commit ec6b5fa
Show file tree
Hide file tree
Showing 3 changed files with 100 additions and 1 deletion.
17 changes: 16 additions & 1 deletion 0104_Maximum Depth of Binary Tree/MaximumDepthofBinaryTree.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,20 @@
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/

public class MaximumDepthofBinaryTree {
public class Solution {
public int maxDepth(TreeNode root) {
if(root == null) return 0;
return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;
Expand Down
40 changes: 40 additions & 0 deletions 0104_Maximum Depth of Binary Tree/MaximumDepthofBinaryTree2.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/

public class Solution {
public int maxDepth(TreeNode root) {
if(root == null) {
return 0;
}
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
int count = 0;
while(!queue.isEmpty()) {
int size = queue.size();
while(size-- > 0) {
TreeNode node = queue.poll();
if(node.left != null) {
queue.offer(node.left);
}
if(node.right != null) {
queue.offer(node.right);
}
}
count++;
}
return count;
}
}
44 changes: 44 additions & 0 deletions 0104_Maximum Depth of Binary Tree/MaximumDepthofBinaryTree3.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/

public class Solution {

public int maxDepth(TreeNode root) {
if(root == null) {
return 0;
}

Stack<TreeNode> stack = new Stack<>();
Stack<Integer> value = new Stack<>();
stack.push(root);
value.push(1);
int max = 0;
while(!stack.isEmpty()) {
TreeNode node = stack.pop();
int temp = value.pop();
max = Math.max(temp, max);
if(node.left != null) {
stack.push(node.left);
value.push(temp+1);
}
if(node.right != null) {
stack.push(node.right);
value.push(temp+1);
}
}
return max;
}
}

0 comments on commit ec6b5fa

Please sign in to comment.