Topic:
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.
test instructions and Analysis: find the lowest height of a binary tree, that is, the shortest path of the root node to the leaf node. Traverse the binary tree, then use a variable to save the traverse to the current node's minimum path, and then each encounter the leaf node, the current leaf node height and the previous minimum path, take a smaller value as the current minimum path.
Code:
/*** Definition for a binary tree node. * public class TreeNode {* int val; * TreeNode left; * TreeNode rig Ht * TreeNode (int x) {val = x;} }*/ Public classSolution { Public intmindepth (TreeNode root) {if(root==NULL)return0; int[] MinHeight = {0}; GetHeight (MinHeight,1, Root); returnMinheight[0]; } Public voidGetHeight (int[] MinHeight,intHeight,treenode node) {//traverse the tree to get the height of each point if(node.left!=NULL) {getheight (minheight,height+1, Node.left); } if(node.right!=NULL) {getheight (minheight,height+1, Node.right); } if(node.left==NULL&&node.right==NULL){//make a judgment on the root node to see if it is the current minimum if(minheight[0]!=0) {//the current child node height is compared to the previous minimum valueMinheight[0]=math.min (height,minheight[0]); }Else{//First time initializationminheight[0]=height; } } }}
[Leetcode] 111. Minimum Depth of Binary Tree Java