LEETCODE--Minimum Depth of Binary Tree

来源:互联网 发布:淘宝壹心表行全是好评 编辑:程序博客网 时间:2024/05/29 08:08

Given a binary tree, find its minimum depth.

The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.

Subscribe to see which companies asked this question

/** * Definition for a binary tree node. * struct TreeNode { *     int val; *     TreeNode *left; *     TreeNode *right; *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public:    int minlevel = 0;    int minDepth(TreeNode* root) {        if(!root)            return 0;        if(!root->left && !root->right)            return 1;        int leftdepth = minDepth(root->left);        int rightdepth = minDepth(root->right);        if(leftdepth == 0)            return rightdepth+1;        if(rightdepth == 0)            return leftdepth+1;        return min(leftdepth,rightdepth)+1;    }};
0 0
原创粉丝点击