111. Minimum Depth of Binary Tree

Given a binary tree, find its minimum depth. Minimum depth is the number of nodes on the shortest path from the root node to the next leaf node. Note: A leaf is a node that has no children. Example 1: Input: Root = [3,9,20,null,null,15,7] Output: 2 Example 2: Input: Root = [2,null,3, null,4,null,5,null,6] Output: 5 Limits: The range of nodes in the tree is [0, 105]. -1000 <= Node.val <= 1000 Solution /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { public: int solve(TreeNode *root){ if(root==NULL){ return 0; } if(root->left == NULL && root->right ==NULL){ return 1; } int l = solve(root->left); int r = solve(root->right); if(l!=0 && r!=0){ return 1+min(l,r); } else if(l==0){ return 1+r; } else if(r==0){ return 1+l; } // return 1+min(l,r); return -1; } int minDepth(TreeNode* root) { return solve(root); } };

Comments

Popular posts from this blog

1431. Kids With the Greatest Number of Candies

125. Valid Palindrome

771. Jewels and Stones