Minimum Depth of Binary Tree
Posted codingEskimo
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Minimum Depth of Binary Tree相关的知识,希望对你有一定的参考价值。
This question is a little bit harder than the Max Depth. We only compare the depth of the leaf node. If it is missing one side, this level shouldn‘t be considered.
/** * Definition of TreeNode: * public class TreeNode { * public int val; * public TreeNode left, right; * public TreeNode(int val) { * this.val = val; * this.left = this.right = null; * } * } */ public class Solution { /** * @param root: The root of binary tree. * @return: An integer. */ public int minDepth(TreeNode root) { // write your code here if (root == null) { return 0; } int left = minDepth(root.left); int right = minDepth(root.right); int minDepth = 0; if ((left == 0 && right != 0) || (left != 0 && right == 0)) { minDepth = Math.max(left, right); } else { minDepth = Math.min(left, right); } return minDepth + 1; } }
The clearer way to do it:
/** * Definition of TreeNode: * public class TreeNode { * public int val; * public TreeNode left, right; * public TreeNode(int val) { * this.val = val; * this.left = this.right = null; * } * } */ public class Solution { /** * @param root: The root of binary tree. * @return: An integer. */ public int minDepth(TreeNode root) { // write your code here if (root == null) { return 0; } return getMin(root); } private int getMin(TreeNode root) { //The null will not be selected since we will get min later if (root == null) { return Integer.MAX_VALUE; } //If it is leaf node, count as 1 depth if (root.left == null && root.right == null) { return 1; } return Math.min(getMin(root.left), getMin(root.right)) + 1; } }
以上是关于Minimum Depth of Binary Tree的主要内容,如果未能解决你的问题,请参考以下文章
111. Minimum Depth of Binary Tree
[LeetCode]题解(python):111 Minimum Depth of Binary Tree
111. Minimum Depth of Binary Tree