leetcode_111_Minimum Depth of Binary Tree

来源:互联网 发布:詹姆斯16年总决赛数据 编辑:程序博客网 时间:2024/05/21 06:56

欢迎大家阅读参考,如有错误或疑问请留言纠正,谢谢微笑


 Minimum Depth of Binary Tree

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)自顶向下逐层累加的,而高度是从叶节点开始(其高度为1)自底向上逐层累加的。


class Solution {private:    int depth=0;    void minDepthUtil(TreeNode *root , int d)    {        if(root->left==NULL && root->right==NULL)        {             depth = d < depth || depth == 0 ? d : depth;        }        else        {            if(root->left!=NULL)                minDepthUtil( root->left , d+1 );            if(root->right!=NULL)                minDepthUtil( root->right , d+1 );        }    }    public:    int minDepth(TreeNode *root) {        if(root == NULL)            return 0;        minDepthUtil( root,1 );        return depth;    }};



//另一种写法class Solution {public:    int minDepth(TreeNode *root) {        // Start typing your C/C++ solution below        // DO NOT write int main() function        if(root == NULL) return 0;                if(root->left == NULL) return minDepth(root->right)+1;        else if(root->right == NULL) return minDepth(root->left)+1;        else return min(minDepth(root->left), minDepth(root->right))+1;    }};


1 0
原创粉丝点击