[Leetcode] 111. Minimum Depth of Binary Tree Java

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.