LeetCode 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.

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


阅读更多
文章标签: java leetcode DFS
个人分类: 算法/oj
上一篇LeetCode Balanced Binary Tree
下一篇LeetCode Path Sum
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭