Created
February 28, 2015 19:32
-
-
Save dmnugent80/80cff473abf8c38efccb to your computer and use it in GitHub Desktop.
Get Min Depth of Binary Tree from Root
This file contains hidden or 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
/** | |
* 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