LeetCode 111. Minimum Depth of Binary Tree

来源:互联网 发布:江南大学北美学院 知乎 编辑:程序博客网 时间:2024/06/16 18:11

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.

根结点到根结点不算路径,比如输入[1,2],输出2.

/** * 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 minDepth(TreeNode* root) {        if(!root) return 0;        int left = 0, right = 0;        if(root->left)          left = minDepth(root->left);        if(root->right)          right = minDepth(root->right);        if(left && right)        return min(left, right) + 1;        else if(left) return left + 1;        else return right + 1;            }};


0 0
原创粉丝点击