[leetcode]111. Minimum Depth of Binary Tree@Java解题报告

来源:互联网 发布:耳机煲机的音乐知乎 编辑:程序博客网 时间:2024/06/05 06:26

https://leetcode.com/problems/minimum-depth-of-binary-tree/description/


Given a binary tree, find its minimum depth.

The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.




package go.jacob.day807;/** * 111. Minimum Depth of Binary Tree * @author Jacob * */public class Demo5 {/* * 方法一 */public int minDepth(TreeNode root) {        if(root == null) return 0;        int left = minDepth(root.left);        int right = minDepth(root.right);        return (left == 0 || right == 0) ? left + right + 1: Math.min(left,right) + 1;           }/* * 方法二 */public int minDepth_1(TreeNode root) {if(root==null)return 0;if(root.left==null)return 1+minDepth(root.right);if(root.right==null)return 1+minDepth(root.left);return 1+Math.min(minDepth(root.left), minDepth(root.right));}}