代码随想录算法训练营第16天|【二叉树03】104. 二叉树的最大深度,111.二叉树的最小深度,222.完全二叉树的节点个数

状态:1刷
二刷有精力的时候 再去掌握迭代法


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

题目:
给定一个二叉树,找出其最大深度。二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。

思路:
递归法:

  1. 确定递归函数的参数和返回值: 参数就是传入树的根节点,返回就返回这棵树的深度
  2. 确定终止条件:如果为空节点的话,就返回0,表示高度为0。
  3. 确定单层递归的逻辑:先求它的左子树的深度,再求右子树的深度,最后取左右深度最大的数值 再+1 (加1是因为算上当前中间节点)就是目前节点为根节点的树的深度。

代码:

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

精简代码:

class Solution {
public:
    int maxDepth(TreeNode* root) {
        if (root == NULL) return 0;
        return 1 + max(maxDepth(root->left), maxDepth(root->right));
    }
};

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

题目: 给定一个二叉树,找出其最小深度。

思路:
使用后序遍历,从下往上递归
代码:

class Solution {
public:
    int getDepth(TreeNode* root) {
        if (root == NULL) return 0;
        int leftDepth = getDepth(root->left);
        int rightDepth = getDepth(root->right);
        if (root->left == NULL && root->right !=NULL) {
            return rightDepth + 1;
        }
        if (root->left != NULL && root->right == NULL) {
            return leftDepth + 1;
        }
        int result = 1 + min(leftDepth, rightDepth);
        return  result;
    }
    int minDepth(TreeNode* root) {
        return getDepth(root);
    }
};

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

题目:
给出一个完全二叉树,求出该树的节点个数。

思路:

  1. 确定递归函数的参数和返回值:int
  2. 确定终止条件:如果为空节点的话,就返回0
  3. 确定单层递归的逻辑:先求它的左子树的节点数量,再求右子树的节点数量,最后取总和再加一 (加1是因为算上当前中间节点)就是目前节点为根节点的节点数量。

代码:
普通二叉树:

/**
 // 版本二 精简版
class Solution {
public:
    int countNodes(TreeNode* root) {
        if (root == NULL) return 0;
        return 1 + countNodes(root->left) + countNodes(root->right);
    }
};
 */
class Solution {
public:
    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;
    }
    int countNodes(TreeNode* root) {
        return getNodesNum(root);
    }
};

总结

二刷有精力的时候 再去掌握迭代法

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值