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