-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMaximumDepthBinaryTree_104.java
More file actions
67 lines (58 loc) · 1.87 KB
/
MaximumDepthBinaryTree_104.java
File metadata and controls
67 lines (58 loc) · 1.87 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
62
63
64
65
66
67
/**
* ----------------------------------------------------------------------------
Maximum Depth of Binary Tree
- 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.
* ----------------------------------------------------------------------------
*/
/**
* Related: 111 Minimum Depth of Binary Tree
*/
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
/**
* 1. Recursion
*/
public class Solution {
public int maxDepth(TreeNode root) {
if (root == null) return 0;
return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;
}
}
//------------------------------------------------------------------------------
/**
* 2. Postorder
* - Preorder & Inorder only push the left tree into stack
* - The maxlength is the longest stack depth
**/
public class Solution {
public int maxDepth(TreeNode root) {
Stack<TreeNode> stack = new Stack<TreeNode>();
TreeNode curr = root, lastvisit = null;
int maxlength = 0;
while (curr != null || !stack.isEmpty()) {
if(curr != null) {
stack.push(curr); lastvisit = curr;
if (curr.left != null) { curr = curr.left; continue; }
else { curr = curr.right; continue; }
}
maxlength = Math.max(maxlength, stack.size());
curr = stack.pop();
if(curr.right == null || curr.right == lastvisit) {
// return from right
lastvisit = curr; curr = null;
}else{ //return from left
stack.push(curr); lastvisit = curr; curr = curr.right;
}
}
return maxlength;
}
}