二叉树的深度

来源:互联网 发布:电信网络测速112 编辑:程序博客网 时间:2024/06/05 15:52

最大深度

class Solution {public:    int TreeDepth(TreeNode* pRoot)    {    if(pRoot==NULL)            return 0;        int l=TreeDepth(pRoot->left)+1;        int r=TreeDepth(pRoot->right)+1;        return max(l,r);    }};
最小深度

class Solution {public:    int run(TreeNode *root) {        if(!root)            return 0;        int l = run(root->left);        int r = run(root->right);        if(l==0 || r==0)            return 1+l+r;        return 1+min(l,r);    }};
求二叉树的最大深度时,只需要考虑节点左右子树的最大值即可,单子树的情况不需要考虑;而二叉树的最小深度,当只有单个子时,子树深度就是最小深度,所以此种情况需要考虑,否则会出现深度为0的问题。


0 0