Leetcode: minimum_depth_of_binary_tree solution,
I. Question
Similar to finding the deepest binary tree, a given binary tree is used to find its minimum depth. The minimum depth is the shortest path from the root node to the leaf node.
Ii. Analysis
When I saw this question, I directly changed the code of the deepest binary tree and changed max to min. I thought it was okay. Who knows WA twice, I calmed down and looked at it. I finally learned that it would end when a node is NULL. So we need to calm down and analyze simple questions next time, otherwise it will be prone to errors.
/*** Definition for binary tree * struct TreeNode {* int val; * TreeNode * left; * TreeNode * right; * TreeNode (int x): val (x ), left (NULL), right (NULL) {}*}; */class Solution {public: int minDepth (TreeNode * root) {if (root = NULL) return 0; int mleft = minDepth (root-> left); int mright = minDepth (root-> right); if (mleft = 0) return 1 + mright; else if (mright = 0) return 1 + mleft; else return min (mleft, mrigh T) + 1 ;}; 2. * Definition for binary tree * struct TreeNode {* int val; * TreeNode * left; * TreeNode * right; * TreeNode (int x ): val (x), left (NULL), right (NULL) {}*}; */class Solution {public: int minDepth (TreeNode * root) {// Start typing your C/C ++ solution below // do not write int main () function return minRec (root);} int minRec (TreeNode * root) {if (! Root) return 0; int left = minRec (root-> left); int right = minRec (root-> right); if (left & right) return 1 + min (left, right); if (left | right) return 1 + left + right; return 1 ;}}; iii./*** Definition for binary tree * public class TreeNode {* int val; * TreeNode left; * TreeNode right; * TreeNode (int x) {val = x ;} *} */public class Solution {public int minDepth (TreeNode root) {// Start typing your Java solution below // do not write main () function return minRec (root );} private int minRec (TreeNode root) {if (root = null) return 0; int l = minRec (root. left); int r = minRec (root. right); if (l = 0) return r + 1; if (r = 0) return l + 1; return Math. min (l, r) + 1 ;}}
What is leetcode?
There are many programming and interview questions, which can be compiled and run online. It is difficult. If you can do it all by yourself, it is very helpful for large companies. I just did the questions there.
Can I use the C language for the questions on the leetcode website? Only C ++, java, and python
C ++ is compatible with C language.