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 to the nearest leaf node.
Example
Given a binary tree as follow:
1 / \ 2 3 / 4 5
The minimum depth is 2 .
Test instructions: Find the minimum depth of the binary tree. How should this minimum depth be understood? The contact is more than the maximum depth, that is, the root node to its farthest leaf node distance (including the end), where the distance of course refers to the number of nodes. Obviously, the minimum depth is the distance between the root node and the nearest node. Although it is known that this is the meaning, at the beginning of the understanding is still a bit biased. For example, I think if the root node is only the right subtree, then this minimum depth how to calculate, is not 1, because the left dial hand tree is empty. Later think carefully, actually, the left subtree is empty, if the right subtree is not empty, the root node (and the other nodes) is not the leaf point, but also to continue to seek the depth of the right subtree (corresponding to the code of the 26th and 29 lines), until the leaf node encountered. The code is as follows:
1 /**2 * Definition of TreeNode:3 * public class TreeNode {4 * public int val;5 * Public TreeNode left and right;6 * Public TreeNode (int val) {7 * This.val = val;8 * This.left = This.right = null;9 * }Ten * } One */ A - Public classSolution { - /** the * @paramroot:the root of binary tree - * @return: An integer - */ - Public intmindepth (TreeNode root) { + //Write your code here - if(root==NULL){ + return0; A } at if(root.left==NULL&&root.right==NULL){ - return1; - } - if(root.left==NULL){ - returnMindepth (root.right) +1; - } in if(root.right==NULL){ - returnMindepth (Root.left) +1; to } + returnMath.min (Mindepth (Root.left), mindepth (root.right)) +1; - } the}
155. Minimum Depth of Binary Tree "Lintcode by Java"