《代码随想录》专题:二叉树2




1、对称二叉树

  • 题目链接:101. 对称二叉树

  • 题解
    这道题目的本质是要比较两个树(这两个树是根节点的左右子树),遍历两棵树而且要比较内侧和外侧节点,需要注意的是这不是层序遍历。本题的迭代法中我们使用了队列,当然使用栈也是可以的。此外,还可以使用递归的方法。
    在这里插入图片描述

  • 递归法:

    class Solution {
    public:
        bool compare(TreeNode* left, TreeNode* right) {
            // 首先排除空节点的情况
            if (left == NULL && right != NULL) return false;
            else if (left != NULL && right == NULL) return false;
            else if (left == NULL && right == NULL) return true;
            // 排除了空节点,再排除数值不相同的情况
            else if (left->val != right->val) return false;
    
            // 此时就是:左右节点都不为空,且数值相同的情况
            // 此时才做递归,做下一层的判断
            bool outside = compare(left->left, right->right);   // 左子树:左、 右子树:右
            bool inside = compare(left->right, right->left);    // 左子树:右、 右子树:左
            bool isSame = outside && inside;                    // 左子树:中、 右子树:中 (逻辑处理)
            return isSame;
    
        }
        bool isSymmetric(TreeNode* root) {
            if (root == NULL) return true;
            return compare(root->left, root->right);
        }
    };
    
  • 迭代法
    通过队列来判断根节点的左子树和右子树的内侧和外侧是否相等,如动画所示:
    在这里插入图片描述

    class Solution {
    public:
        bool isSymmetric(TreeNode* root) {
            if (root == NULL) return true;
            queue<TreeNode*> que;
            que.push(root->left);   // 将左子树头结点加入队列
            que.push(root->right);  // 将右子树头结点加入队列
            
            while (!que.empty()) {  // 接下来就要判断这两个树是否相互翻转
                TreeNode* leftNode = que.front(); que.pop();
                TreeNode* rightNode = que.front(); que.pop();
                if (!leftNode && !rightNode) {  // 左节点为空、右节点为空,此时说明是对称的
                    continue;
                }
    
                // 左右一个节点不为空,或者都不为空但数值不相同,返回false
                if ((!leftNode || !rightNode || (leftNode->val != rightNode->val))) {
                    return false;
                }
                que.push(leftNode->left);   // 加入左节点左孩子
                que.push(rightNode->right); // 加入右节点右孩子
                que.push(leftNode->right);  // 加入左节点右孩子
                que.push(rightNode->left);  // 加入右节点左孩子
            }
            return true;
        }
    };
    

2、二叉树的最大深度

  • 题目链接:104.二叉树的最大深度
  • 题解
    • 本题可以使用前序(中左右),也可以使用后序遍历(左右中),使用前序求的就是深度,使用后序求的是高度
      • 二叉树节点的深度:指从根节点到该节点的最长简单路径边的条数或者节点数(取决于深度从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);
        }
    };
    
    使用前序的遍历顺序进行递归,这才是真正求深度的逻辑
    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 == null) 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;
        }
    };
    

3、二叉树的最小深度

  • 题目链接: 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) { 
                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 {
    private:
        int result;
        void getdepth(TreeNode* node, int depth) {
            // 函数递归终止条件
            if (root == nullptr) {
                return;
            }
            // 中,处理逻辑:判断是不是叶子结点
            if (root -> left == nullptr && root->right == nullptr) {
                res = min(res, 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;
        }
    };
    
  • 对称二叉树

在这里插入图片描述


4、合并二叉树

  • 题目链接: 617.合并二叉树
  • 题解:使用递归法更好理解,做着做着就出结果了
  • 代码实现
    lass Solution {
    public:
        TreeNode* travelsal(TreeNode* root1,TreeNode* root2){
            if(!root1) return root2;
            if(!root2) return root1;
            TreeNode* root = new TreeNode(root1->val+root2->val);
            /*我自己的解法里把前三行替换成为下面这些内容,结果显而易见是错误的。
            反例:root1为NULL,root2不为NULL,则在求root孩子节点的时候会触发NULL->left,显然是错误的
            因此,遇见这种情况直接返回不为NULL的节点即可*/
    		/*
    		 int value;
    		 if((root1 == NULL) && (root2 == NULL)) return NULL;
    		 if((root1 != NULL) && (root2 != NULL)) value = root1->val + root2->val;
    		 else if(root1) value = root1->val;
    		 else value = root2->val;
    		 TreeNode* root = new TreeNode(value);
            */
            
            root->left = travelsal(root1->left, root2->left);
            root->right = travelsal(root1->right, root2->right);
            return root;
        }
        TreeNode* mergeTrees(TreeNode* root1, TreeNode* root2) {
            return(travelsal(root1,root2));
        }
    };
    
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Elec Liu

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值