代码随想录算法训练营第十六天| 104.二叉树的最大深度、559.n叉树的最大深度、111.二叉树的最小深度 、222.完全二叉树的节点个数

104.二叉树的最大深度

题目链接:104.二叉树的最大深度

此题昨天用层序遍历法解过一次,遍历一层深度就加一,代码可以看上一篇。
这里主要用递归法,注意递归三部曲:返回和传入参数、中止条件、本层逻辑。

此处采用后序遍历,代码比较简单点。

class Solution {
public:
    int getDepth(TreeNode* node) {
        if (node == nullptr) return 0;
        int leftdepth = getDepth(node->left);
        int rightdepth = getDepth(node->right);
        int depth = 1 + max(leftdepth, rightdepth);
        return depth;  //代码还可以简洁,但是看不出实现的原理来了,此处是后序遍历
    }
    int maxDepth(TreeNode* root) {
        if (root == nullptr) return 0;
        return getDepth(root);
    }
};

559.n叉树的最大深度

题目链接:559.n叉树的最大深度

此题和二叉树的深度一样,只不过子节点不是两个了。

class Solution {
public:
    int getdepth(Node* node) {
        if (node == nullptr) return 0;
        int childdepth = 0;
        for (Node* child : node->children) {
            int d = getdepth(child);
            childdepth = childdepth > d ? childdepth : d;
        }
        return 1 + childdepth;
    }
    int maxDepth(Node* root) {
        return getdepth(root);
    }
};

111.二叉树的最小深度

题目链接:111.二叉树的最小深度

此题和最大深度有点类似,只不过得注意左或者右节点为空,不算叶子节点

class Solution {
public:
    int getdepth(TreeNode* node) {
        if (node == nullptr) return 0;
        int leftdepth = getdepth(node->left);
        int rightdepth = getdepth(node->right);
        if (node->left == nullptr && node->right != nullptr) { //左节点为空
            return 1 + rightdepth;
        } else if (node->left != nullptr && node->right == nullptr) { //右节点为空
            return 1 + leftdepth;
        }
        return 1 + min(leftdepth, rightdepth);
    }
    int minDepth(TreeNode* root) {
        return getdepth(root);
    }
};

222.完全二叉树的节点个数

题目链接:222.完全二叉树的节点个数

此题有两种解法,一种可以将完全二叉树当做普通二叉树,将节点全部遍历一遍,但时间复杂度高
另一种是利用满二叉树的特性,深度为n的层的满二叉树的节点数为2^n-1
遍历最左边和最右边,如果深度相等,即为满二叉树

1. 普通二叉树

class Solution {
public:
    int getnum(TreeNode* node) {
        if (node == nullptr) return 0;
        int leftnum = getnum(node->left);
        int rightnum = getnum(node->right);
        int num = leftnum + rightnum + 1;
        return num;
    }
    int countNodes(TreeNode* root) {
        return getnum(root);
    }
};

2. 完全二叉树

class Solution {
public:
    int getnum(TreeNode* node) {
        if (node == nullptr) return 0;
        TreeNode* left = node->left;
        TreeNode* right = node->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; //移位运算 2<<1表示2^2
        }
        return getnum(node->left) + getnum(node->right) + 1;
    }
    int countNodes(TreeNode* root) {
        return getnum(root);
    }
};

总结

一入递归深似海,想明白递归的逻辑,代码非常简洁和优雅。

你可能感兴趣的:(leetcode刷题打卡,算法,leetcode,数据结构)