Minimum Depth of Binary Tree

来源:互联网 发布:怎样建立网络共享 编辑:程序博客网 时间:2024/05/16 06:21

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.

左右子树分别算深度,返回较小值,但如果一方为空直接返回另一方的深度。

class Solution {public:    int calMinDepth(TreeNode *node)    {        if(node==NULL)        {            return 0;        }            if((node->left==NULL) && (node->right==NULL))        {            return 1;        }                int leftDepth = 0;        int rightDepth = 0;                if(node->left!=NULL)        {            leftDepth = calMinDepth(node->left) + 1;        }                if(node->right!=NULL)        {            rightDepth = calMinDepth(node->right) + 1;        }                if(node->left!=NULL && node->right!=NULL)        {            if(leftDepth <= rightDepth)            {                return leftDepth;            }            else            {                return rightDepth;            }        }                if(node->left==NULL)            return rightDepth;        if(node->right==NULL)            return leftDepth;    }    public:    int minDepth(TreeNode *root) {                return calMinDepth(root);            }};


0 0
原创粉丝点击