15算法课程 111. Minimum Depth of Binary Tree

来源:互联网 发布:datagard 数据同步 编辑:程序博客网 时间:2024/06/05 19:56


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.


solution:

本题思路递归,为了求最小值,那么在递归返回时只要返回左右子树的的较小值即可,但是要注意特殊情况即存在左或右子树不存在的情况,此时递归返回值要返回左右子树较大的值。


code:

class Solution {public:    int minDepth(TreeNode* root) {        if(root==NULL)            return 0;        int leftDepth = minDepth(root->left);        int rightDepth = minDepth(root->right);        if(rightDepth==0||leftDepth==0)            return max(leftDepth,rightDepth)+1;        else            return min(leftDepth,rightDepth)+1;    }};




原创粉丝点击