【leetcode】【111】Minimum Depth of Binary Tree

来源:互联网 发布:云计算基地建设成本 编辑:程序博客网 时间:2024/05/16 05:14

一、问题描述

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.

二、问题分析

递归解法,判断左右两边子树哪个depth最小,要注意如果有个节点只有一边孩子时,不能返回0,要返回另外一半边的depth(自己稍微画几个树就可以理解了)。

三、Java AC 代码

public int minDepth(TreeNode root) {return minLev(root);}public int minLev(TreeNode node){if (node==null) {return 0;}int leftLev = minLev(node.left);int rightLev = minLev(node.right);if (leftLev==0) {return  rightLev+1;}if (rightLev==0) {return leftLev+1;}return Math.min(leftLev, rightLev) + 1;}



0 0
原创粉丝点击