【每日算法】

算法第16天| (二叉树part03) 104.二叉树的最大深度 559.n叉树的最大深度 111.二叉树的最小深度 222.完全二叉树的节点个数


二叉树理论基础
ps: 迭代法可以直接过,二刷有精力的时候再去掌握迭代法。

一、 104.二叉树的最大深度 (优先掌握递归) 559.n叉树的最大深度

104 题目链接
559 题目链接
代码随想录链接

ps:什么是深度,什么是高度,如何求深度,如何求高度,这里有关系到二叉树的遍历方式。大家要先看视频讲解,就知道以上我说的内容了,很多录友刷过这道题,但理解的还不够。
深度: 二叉树中任意一个节点到根节点的距离,根节点的深度为1.【指从根节点到该节点的最长简单路径边的条数或者节点数(取决于深度从0开始还是从1开始)】
高度:二叉树中任意一个节点到叶子结点的距离.【指从该节点到叶子节点的最长简单路径边的条数或者节点数(取决于高度从0开始还是从1开始)】
在二叉树的遍历中如何求高度?—求高度用后序遍历(因为高度是到叶子节点的距离,所以求高度,需要从下往上遍历;采用后序遍历-左右中的顺序,把处理逻辑(中)放在最后,可以把叶子节点的高度返回其父节点,父节点的高度即为它的叶子节点的高度+1);
在二叉树的遍历中如何求深度?—求深度用前序遍历;(因为深度是到根节点的距离,所以求深度是从上往下遍历,中左右,"中"包含了处理过程)
关键:根节点的高度就是二叉树的最大深度
先用后序遍历(左右中)来计算树的高度。

  1. 确定递归函数的参数和返回值:参数就是传入树的根节点,返回就返回这棵树的深度,所以返回值为int类型。
int getdepth(TreeNode* node)
  1. 确定终止条件:如果为空节点的话,就返回0,表示高度为0。因为叶子节点的高度为1.
if (node == NULL) return 0;
  1. 确定单层递归的逻辑:先求左子树的深度,再求右子树的深度,最后取左右深度最大的数值 再+1 (加1是因为算上当前中间节点)就是目前节点为根节点的树的深度。
int leftdepth = getdepth(node->left);       // 左
int rightdepth = getdepth(node->right);     // 右
int depth = 1 + max(leftdepth, rightdepth); // 中
return depth;
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);
    }
};

精简后的代码:

class Solution {
public:
    int maxDepth(TreeNode* root) {
        if (root == null) return 0;
        // 把左右中return合并成一行
        return 1 + max(maxDepth(root->left), maxDepth(root->right));
    }
};

本题当然也可以使用前序,代码如下:(充分表现出求深度回溯的过程,前中后序的遍历顺序)

class Solution {
public:
    int result;
    void getdepth(TreeNode* node, int depth) {
        result = depth > result ? depth : result; // 中

        if (node->left == NULL && node->right == NULL) return ;

        if (node->left) { // 左
            depth++;    // 深度+1
            getdepth(node->left, depth);
            depth--;    // 回溯,深度-1
        }
        if (node->right) { // 右
            depth++;    // 深度+1
            getdepth(node->right, depth);
            depth--;    // 回溯,深度-1
        }
        return ;
    }
    int maxDepth(TreeNode* root) {
        result = 0;
        if (root == NULL) return result;
        getdepth(root, 1);
        return result;
    }
};

简化后的代码:

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

使用迭代法的话,使用层序遍历是最为合适的,因为最大的深度就是二叉树的层数,和层序遍历的方式极其吻合。在二叉树中,一层一层的来遍历二叉树,记录一下遍历的层数就是二叉树的深度。

class Solution {
public:
    int maxDepth(TreeNode* root) {
        if (root == NULL) return 0;
        int depth = 0;
        queue<TreeNode*> que;
        que.push(root);
        while(!que.empty()) {
            int size = que.size();
            depth++; // 记录深度
            for (int i = 0; i < size; i++) {
                TreeNode* node = que.front();
                que.pop();
                if (node->left) que.push(node->left);
                if (node->right) que.push(node->right);
            }
        }
        return depth;
    }
};

给定一个 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;
    }
};

迭代法代码:

class Solution {
public:
    int maxDepth(Node* root) {
        queue<Node*> que;
        if (root != NULL) que.push(root);
        int depth = 0;
        while (!que.empty()) {
            int size = que.size();
            depth++; // 记录深度
            for (int i = 0; i < size; i++) {
                Node* node = que.front();
                que.pop();
                for (int j = 0; j < node->children.size(); j++) {
                    if (node->children[j]) que.push(node->children[j]);
                }
            }
        }
        return depth;
    }
};

二、 111.二叉树的最小深度 (优先掌握递归)

翻转二叉树
代码随想录链接
最小深度和最大深度看似差不多,但事实上差距很大。
最小深度:题目要求是 从根节点到最近叶子节点的距离。
思路: 通过后序遍历求最小深度,来求出符合题目要求的最小深度的值。
注意避坑:
题目中说的是:最小深度是从根节点到最近叶子节点的最短路径上的节点数量。注意是叶子节点。
什么是叶子节点???左右孩子都为空的节点才是叶子节点!
在这里插入图片描述 递归三部曲:

  1. 确定递归函数的参数和返回值:参数为要传入的二叉树根节点,返回的是int类型的深度。
int getDepth(TreeNode* node)
  1. 确定终止条件

终止条件也是遇到空节点返回0,表示当前节点的高度为0。

if (node == NULL) return 0;
  1. 确定单层递归的逻辑:这块和求最大深度可就不一样了,如果写成如下代码:
int leftDepth = getDepth(node->left);
int rightDepth = getDepth(node->right);
int result = 1 + min(leftDepth, rightDepth);
return result;

如果这么求的话,没有左孩子的分支会算为最短深度。但是这并不符合题目最小深度的要求。题目中说的是:最小深度是从根节点到最近叶子节点的最短路径上的节点数量。注意是叶子节点——左右孩子都为空的节点才是叶子节点!

因此正确的逻辑应该是:
如果左子树为空,右子树不为空,说明最小深度是 1 + 右子树的深度。
反之,右子树为空,左子树不为空,最小深度是 1 + 左子树的深度。 最后如果左右子树都不为空,返回左右子树深度最小值 + 1 。

// 左子树 向左递归
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;

遍历的顺序为后序(左右中),可以看出:求二叉树的最小深度和求二叉树的最大深度的差别主要在于处理左右孩子不为空的逻辑。
整体递归法代码:

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);
    }
};

递归法精简后代码:

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

前序遍历:

class Solution {
private:
    int result;
    void getdepth(TreeNode* node, int depth) {
        // 函数递归终止条件
        if (node == nullptr) {
            return;
        }
        // 中,处理逻辑:判断是不是叶子结点
        if (node -> left == nullptr && node->right == nullptr) {
            result = min(result, depth);
        }
        if (node->left) { // 左
            getdepth(node->left, depth + 1);
        }
        if (node->right) { // 右
            getdepth(node->right, depth + 1);
        }
        return ;
    }

public:
    int minDepth(TreeNode* root) {
        if (root == nullptr) {
            return 0;
        }
        result = INT_MAX;
        getdepth(root, 1);
        return result;
    }
};

迭代法—层序遍历代码:
需要注意的是,只有当左右孩子都为空的时候,才说明遍历到最低点了。如果其中一个孩子不为空则不是最低点

class Solution {
public:

    int minDepth(TreeNode* root) {
        if (root == NULL) return 0;
        int depth = 0;
        queue<TreeNode*> que;
        que.push(root);
        while(!que.empty()) {
            int size = que.size();
            depth++; // 记录最小深度
            for (int i = 0; i < size; i++) {
                TreeNode* node = que.front();
                que.pop();
                if (node->left) que.push(node->left);
                if (node->right) que.push(node->right);
                if (!node->left && !node->right) { // 当左右孩子都为空的时候,说明是最低点的一层了,退出
                    return depth;
                }
            }
        }
        return depth;
    }
};

三、 222.完全二叉树的节点个数(优先掌握递归)

题目链接
代码随想录链接
求节点个数其实是模板题目,使用递归法的前中后序遍历,或者迭代法中的层序遍历都可以求树的节点个数,本题强调了是完全二叉树,因此尽量使用完全二叉树的特性。
不考虑二叉树特性的 普通解法:

// 版本一
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);
    }
};

// 版本二 精简后代码(初学者建议学习版本一的代码,稳稳的打基础)
class Solution {
public:
    int countNodes(TreeNode* root) {
        if (root == NULL) return 0;
        return 1 + countNodes(root->left) + countNodes(root->right);
    }
};

迭代法只要模板少做改动,加一个变量result,统计节点数量就可以了

class Solution {
public:
    int countNodes(TreeNode* root) {
        queue<TreeNode*> que;
        if (root != NULL) que.push(root);
        int result = 0;
        while (!que.empty()) {
            int size = que.size();
            for (int i = 0; i < size; i++) {
                TreeNode* node = que.front();
                que.pop();
                result++;   // 记录节点数量
                if (node->left) que.push(node->left);
                if (node->right) que.push(node->right);
            }
        }
        return result;
    }
};

时间复杂度:O(n)
空间复杂度:O(n)

利用完全二叉树的特性 解法:
判断其子树是不是满二叉树,如果是满二叉树,则直接利用公式计算这个子树(满二叉树)的节点数量,如果不是则继续递归,那么 在递归三部曲中,第二步:终止条件的写法应该是这样的:

if (root == nullptr) return 0; 
// 开始根据左深度和右深度是否相同来判断该子树是不是满二叉树
// 定义左右指针遍历计算左右侧的深度
TreeNode* left = root->left;
TreeNode* right = root->right;
// 这里统计深度的时候是从0开始算的,后面return 位运算--2 << leftDepth,
int leftDepth = 0, rightDepth = 0; // 这里初始为0是有目的的,为了下面求指数方便
while (left) {  // 求左子树深度
    // 左侧指针一路向左
    left = left->left;
    // 深度++
    leftDepth++;
}
while (right) { // 求右子树深度
    // 右侧指针一路向右
    right = right->right;
    // 深度++
    rightDepth++;
}
// 如果左右子树深度相等,那么在整个二叉树是完全二叉树的条件下,该子树为满二叉树;可以直接利用公式快速计算该子树的节点数量
if (leftDepth == rightDepth) {
    // 直接额return节点数量;采用位运算,2<<左移一位相当于2的2次方;2<<左移0位相当于2的1次方,也就是从1开始 计数树的深度的
    return (2 << leftDepth) - 1; // 注意(2<<1) 相当于2^2,返回满足满二叉树的子树节点数量
}

单层递归的逻辑:

// 向左遍历得到左子树的节点数量
int leftTreeNum = countNodes(root->left);       // 左
// 向右遍历得到右子树的节点数量
int rightTreeNum = countNodes(root->right);     // 右
int result = leftTreeNum + rightTreeNum + 1;    // 中
return result;

简化后:

return countNodes(root->left) + countNodes(root->right) + 1; 

完整的 考虑了完全二叉树特性的递归法代码:

class Solution {
public:
    int countNodes(TreeNode* root) {
        if (root == nullptr) return 0;
        TreeNode* left = root->left;
        TreeNode* right = root->right;
        int leftDepth = 0, rightDepth = 0; // 这里初始为0是有目的的,为了下面求指数方便
        while (left) {  // 求左子树深度
            left = left->left;
            leftDepth++;
        }
        while (right) { // 求右子树深度
            right = right->right;
            rightDepth++;
        }
        if (leftDepth == rightDepth) {
            return (2 << leftDepth) - 1; // 注意(2<<1) 相当于2^2,所以leftDepth初始为0
        }
        return countNodes(root->left) + countNodes(root->right) + 1;
    }
};

时间复杂度:O(log n × log n)
空间复杂度:O(log n)

参考链接:
作者:力扣官方题解
链接:
https://leetcode.cn/problems/binary-tree-level-order-traversal/solutions/241885/er-cha-shu-de-ceng-xu-bian-li-by-leetcode-solution/
https://leetcode.cn/problems/symmetric-tree/solutions/268109/dui-cheng-er-cha-shu-by-leetcode-solution/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值