Skip to content

Instantly share code, notes, and snippets.

@wayetan
Created December 23, 2013 06:36
Show Gist options
  • Save wayetan/8092589 to your computer and use it in GitHub Desktop.
Save wayetan/8092589 to your computer and use it in GitHub Desktop.
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.
*/
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public int maxDepthRecursive(TreeNode root) {
if(root == null) return 0;
int left_Depth = maxDepthRecursive(root.left);
int right_Depth = maxDepthRecursive(root.right);
return (left_Depth > right_Depth) ? left_Depth + 1 : right_Depth + 1;
}
}
/**
* Postorder iterative traversal
*/
public class Solution{
public int maxDepthIterative(TreeNode root){
if(root == null) return 0;
Stack<TreeNode> s = new Stack<TreeNode>();
s.push(root);
int maxDepth = 0;
TreeNode prev = null;
while(!s.isEmpty()){
TreeNode curr = s.peek();
if(prev == null || prev.left == curr || prev.right == curr){
if(curr.left != null) s.push(curr.left);
else if(curr.right != null) s.push(curr.right);
}else if(curr.left == prev){
if(curr.right != null) s.push(curr.right);
}else
s.pop();
prev = curr;
if(s.size() > maxDepth)
maxDepth = s.size();
}
return maxDepth;
}
}
public class Solution {
public int maxDepthLevelOrder(TreeNode root){
if(root == null)
return 0;
int res = 1;
Queue<TreeNode> q = new LinkedList<TreeNode>();
q.offer(root);
q.offer(null);
while(!q.isEmpty()){
TreeNode tmp = q.poll();
if(tmp != null){
if(tmp.left != null)
q.offer(tmp.left);
if(tmp.right != null)
q.offer(tmp.right);
}else{
if(!q.isEmpty()){
++res;
q.offer(null);
}
}
}
return res;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment