LeetCode Minimum Depth of Binary Tree

原创 2015年07月07日 09:59:09

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.

Solution:

DFS即可。

import java.util.*;

public class Solution {

	public int minDepth(TreeNode root) {
		if (root == null)
			return 0;
		return depth(root);
	}

	int depth(TreeNode root) {
		// if (root.left == null && root.right == null)
		// return 1;
		int ret = Integer.MAX_VALUE;
		if (root.left != null)
			ret = Math.min(depth(root.left), ret);
		if (root.right != null)
			ret = Math.min(depth(root.right), ret);

		if (ret == Integer.MAX_VALUE)
			ret = 1;
		else
			ret++;

		return ret;
	}
}


版权声明:本文为博主原创文章,未经博主允许不得转载。

相关文章推荐

LeetCode(111)Minimum Depth of Binary Tree

题目如下: Given a binary tree, find its minimum depth. The minimum depth is the number of nodes along th...

leetcode解题之Maximum/Minimum Depth of Binary Tree Java版(树的最大、最小深度)

leetcode解题之104# Maximum Depth of Binary Tree Java版(树的最大深度),111. Minimum Depth of Binary Tree(树的最大深度...

【leetcode】111. Minimum Depth of Binary Tree

一、题目描述 Given a binary tree, find its minimum depth. The minimum depth is the number of nodes...

LeetCode 111. Minimum Depth of Binary Tree(二叉树最小深度)

原题网址:https://leetcode.com/problems/minimum-depth-of-binary-tree/ Given a binary tree, find its min...

Leetcode_111_Minimum Depth of Binary Tree

本文是在学习中的总结,欢迎转载但请注明出处:http://blog.csdn.net/pistolove/article/details/41964249 Given a binary tree, ...

LeetCode:Minimum Depth of Binary Tree

LeetCode第二话,其实中间也写了其他题,但是较为简单,就不赘述了。这道题,一上来,又理解错了,一直以为是用广度优先来一层一层的搜索哪个节点没有两个子节点。结果一测试,当只有两个节点时,结果居然为...

leetcode笔记--Minimum Depth of Binary Tree

Minimum Depth of Binary Tree 题目:难度(Easy) Given a binary tree, find its minimum depth. The minimum de...

【LeetCode】Minimum Depth of Binary Tree 解题报告

Minimum Depth of Binary Tree[LeetCode]Given a binary tree, determine if it is height-balanced. For ...

Leetcode_Minimum Depth of Binary Tree

题意为得出二叉树的最小深度,但深度是定义为从根节点到叶子节点的最少节点数。 容易出错的地方:为空节点时,直接返回0。这是不对的,要判断其是否有兄弟节点,没有兄弟节点的时候才能返回0,即这个节点的父节...

LeetCode111 Minimum Depth of Binary Tree

详细见:leetcode.com/problems/minimum-depth-of-binary-tree Java Solution: github package leetcod...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

(最多只允许输入30个字)