代码随想录算法训练营Day 16|LeetCode104 二叉树的最大深度、LeetCode559 n叉树最大深度、eetcode111 二叉树的最小深度、Leetcode222 完全二叉树的节点个数

LeetCode104 二叉树的最大深度

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

思路

本题采用后序递归遍历可得到根节点的高度,即为二叉树的最大深度,比较好写。真正求深度的逻辑则是采用前序遍历(回溯),补充:

  • 二叉树节点的深度:指从根节点到该节点的最长简单路径边的条数或者节点数(取决于深度从0开始还是从1开始)
  • 二叉树节点的高度:指从该节点到叶子节点的最长简单路径边的条数或者节点数(取决于高度从0开始还是从1开始)

还可以采用层次遍历(迭代法)求出二叉树层数以得到最大深度,详情均可见代码随想录

代码

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

复杂度

时间复杂度:O(n)

空间复杂度:O(height) height为二叉树高度

LeetCode559 n叉树的最大深度

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

思路

同上题,直接附代码

代码

class Solution {
public:
    int maxDepth(Node* root) {
        if (root == nullptr)
            return 0;
        int depth = 0;
        for (int i = 0; i < root->children.size(); i++) {
            depth = max(depth, maxDepth(root->children[i]));
        }
        return depth + 1;
    }
};

复杂度

时间复杂度:O(n)

空间复杂度:O(height)

Leetcode111 二叉树的最小深度

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

思路

求二叉树最小深度看似与求最大深度类似,实则处理起来还是更麻烦一些:最小深度概念为从根节点到最近叶子节点的最短路径上的节点数量,下图中的例子便需要特殊讨论①若左子树为空,右子树不为空,则最小深度为1+右子树最小深度;②若右子树为空,左子树不为空,则最小深度为1+左子树最小深度;③若左右子树都不为空,则最小深度为1+min(左子树最小深度,右子树最小深度)。

代码

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) {
            return 1 + rightDepth;
        }
        // 当一个右子树为空,左不为空
        if (node->left != NULL && node->right == NULL) {
            return 1 + leftDepth;
        }
        int result = 1 + min(leftDepth, rightDepth);
        return result;
    }

    int minDepth(TreeNode* root) { return getDepth(root); }
};

复杂度

时间复杂度:O(n)

空间复杂度:O(height)

Leetcode222 完全二叉树的节点个数

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

思路

与求深度类似,采用后序遍历,将max换成求和,递归后即可得完全二叉树的节点个数。

代码

class Solution {
private:
    int getNodesNum(TreeNode* cur) {
        if (cur == NULL) return 0;
        int leftNum = getNodesNum(cur->left);      // 左
        int rightNum = getNodesNum(cur->right);    // 右
        int treeNum = leftNum + rightNum + 1;      // 中
        return treeNum;
    }
public:
    int countNodes(TreeNode* root) {
        return getNodesNum(root);
    }
};

复杂度

时间复杂度:O(n)

空间复杂度:O(height)

  • 7
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值