"One Day together Leetcode" #111. Minimum Depth of Binary Tree

Source: Internet
Author: User

One Day together Leetcode

This series of articles has all been uploaded to my github address: Zeecoder ' s GitHub
You are welcome to follow my Sina Weibo, my Sina Weibo blog
Welcome reprint, Reprint please indicate the source

(i) Title

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.

(ii) Problem solving

To find the minimum height of the binary tree. The minimum height refers to the number of nodes on the shortest path from the root node to the leaf node.
Problem-solving ideas: The idea of recursion, with each node in the two-fork tree as the root node, then its minimum height is equal to the Saozi right subtree of the minimum height plus 1, if there is no Zuozi (right subtree) is equal to the right subtree (left subtree) the minimum height.
See code for specific explanations:

/** * Definition for a binary tree node. * struct TreeNode {* int val; * TreeNode *left; * TreeNode *righ T * TreeNode (int x): Val (x), left (null), right (NULL) {} *}; */classSolution { Public:intMindepth (treenode* root) {if(Root==null)return 0;//If the tree is empty, return 0        returnDfstree (root); }intDfstree (treenode* root) {if(Root==null)returnInt_max;//Use a technique here, the node is empty to return the maximum value, the back does not have to judge that the tree is empty        intleft = Dfstree (Root->left);//Find the minimum height of the left sub-tree        intright = Dfstree (root->right);//Find the minimum height of the right sub-tree        if(Left==int_max&&right==int_max)return 1;//If both left and right subtrees are empty, return 1        returnMin (left,right) +1;//or return the smallest height in the left and right subtree.}};

"One Day together Leetcode" #111. Minimum Depth of Binary Tree

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.