标签:des style blog http color os
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.
思路:递归实现,取左右节点中深度小的+1。
注意:如果左右子树其中一个为null,则应以不为null的子树深度为准,而不是以null的深度0为准。
public class Solution { public int minDepth(TreeNode root) { if (root == null) return 0; if (root.left == null) return minDepth(root.right) + 1; if (root.right == null) return minDepth(root.left) + 1; else { int minLeft = minDepth(root.left); int minRight = minDepth(root.right); return (minLeft < minRight ? minLeft : minRight) + 1; } } public static void main(String[] args) { TreeNode root = new TreeNode(10); root.left = new TreeNode(5); root.right = new TreeNode(5); root.right.left = new TreeNode(9); System.out.println(new Solution().minDepth(root)); } }
[leetcode] Minimum Depth of Binary Tree,布布扣,bubuko.com
[leetcode] Minimum Depth of Binary Tree
标签:des style blog http color os
原文地址:http://www.cnblogs.com/jdflyfly/p/3821430.html