二叉树最大深度和最小深度

来源:互联网 发布:视频cms php 编辑:程序博客网 时间:2024/05/19 14:01

二叉树的最大深度

int maxDepth(TreeNode *root) {        // write your code (here)        if(root == NULL)            return 0;        int leftDepth = maxDepth(root->left);        int rightDepth = maxDepth(root->right);        return leftDepth > rightDepth ? (leftDepth + 1) : (rightDepth + 1);    }

二叉树的最小深度

int minDepth(TreeNode *root) {        // write your code here        if(root == NULL)            return false;        if(root->left == NULL && root->right == NULL)            return 1;        int leftDepth = minDepth(root->left);        if(leftDepth == 0)            leftDepth = INT_MAX;        int rightDepth = minDepth(root->right);        if(rightDepth == 0)            rightDepth = INT_MAX;        return leftDepth < rightDepth ? (leftDepth + 1) : (rightDepth + 1);    }
原创粉丝点击