代码随想录算法训练营第十六天 | 104.二叉树的最大深度、559.N叉树的最大深度、111.二叉树的最小深度

文章目录

  • 一、104.二叉树的最大深度
  • 二、559.N叉树的最大深度
  • 三、111.二叉树的最小深度
  • 四、111.二叉树的最小深度


一、104.二叉树的最大深度

题目链接

代码如下:

class Solution {
public:
    int getHeight(TreeNode* node) {
        if (node == NULL) return 0;
        /*int leftHeight = getHeight(node->left);//左
        int rightHeight = getHeight(node->right);//右
        int height = 1 + max(leftHeight, rightHeight);//中
        return height;*/
        return 1 + max(getHeight(node->left),getHeight(node->right));
    }
    int maxDepth(TreeNode* root) {
        return getHeight(root);
    }
};

二、559.N叉树的最大深度

题目链接

代码如下:

class Solution {
public:
    int maxDepth(Node* root) {
        if (root == 0) return 0;
        int depth = 0;
        for (int i = 0; i < root->children.size(); i++) {
            depth = max(depth, maxDepth(root->children[i])); //返回子节点的最大深度
        }
        return depth + 1; //如果只有一个节点,不会执行for循环,最大深度为1
    }
};

三、111.二叉树的最小深度

题目链接

代码如下:

class Solution {
public:
    int getDepth(TreeNode* node) {
        if (node == NULL) return 0;
        int leftDepth = getDepth(node->left); //左
        int rightDepth = getDepth(node->right); //右
        //中
        if (node->left == NULL && node->right != NULL) {//如果左节点为空,最小深度为1+右子树深度
            return 1 + rightDepth;
        }
        if (node->left != NULL && node->right == NULL) {//如果右节点为空,最小深度为1+左子树深度
            return 1 + leftDepth;
        }
        int result = 1 + min(leftDepth, rightDepth);//左右子树都不为空,才可以用min
        return result;
    }
    int minDepth(TreeNode* root) {
        return getDepth(root);
    }
};

四、111.二叉树的最小深度

题目链接

代码如下:

class Solution {
public:
    int getNum(TreeNode* cur) {
        if (cur == NULL) return 0;
        TreeNode* left = cur->left;
        TreeNode* right = cur->right;
        int leftDepth = 0, rightDepth = 0;
        while (left) {
            left = left->left;
            leftDepth ++;
        }
        while (right) {
            right = right->right;
            rightDepth ++;
        }
        if (leftDepth == rightDepth) return (2<<leftDepth) - 1;//左右深度相等,又是完全二叉树,一定是满二叉树,直接用公式计算节点数量即可

        int leftNum = getNum(cur->left);
        int rightNum = getNum(cur->right);
        int result = leftNum + rightNum + 1;
        return result;
    }
    int countNodes(TreeNode* root) {
        return getNum(root);
    }
};

你可能感兴趣的:(算法,leetcode,深度优先)