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

xiaoxiao2021-02-28  49

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)); } }

转载请注明原文地址: https://www.6miu.com/read-82401.html

最新回复(0)