Skip to content

Instantly share code, notes, and snippets.

@dmnugent80
Created February 28, 2015 19:32
Show Gist options
  • Save dmnugent80/80cff473abf8c38efccb to your computer and use it in GitHub Desktop.
Save dmnugent80/80cff473abf8c38efccb to your computer and use it in GitHub Desktop.
Get Min Depth of Binary Tree from Root
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public int minDepth(TreeNode root) {
if (root == null) return 0;
return minDepthHelper(root, 1);
}
public int minDepthHelper(TreeNode node, int level){
if (node.left == null && node.right == null){
return level;
}
int left = 0;
int right = 0;
int retVal = 0;
if (node.left != null && node.right != null){
left = minDepthHelper(node.left, level + 1);
right = minDepthHelper(node.right, level + 1);
return Math.min(left, right);
}
if (node.left != null)
retVal = minDepthHelper(node.left, level + 1);
if (node.right != null)
retVal = minDepthHelper(node.right, level + 1);
return retVal;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment