DAY14 - 226.翻转二叉树,101. 对称二叉树,104.二叉树的最大深度,111.二叉树的最小深度

226.翻转二叉树

其实就是把二叉树的每一个结点的左右子树都反转

递归写法

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    TreeNode* invertTree(TreeNode* root) {
        if(root==nullptr) return root;
        invertTree(root->left);
        invertTree(root->right);
        swap(root->left,root->right);

        return root;  
    }
};

前序遍历和后序遍历都可以,中序遍历不行。如果让我想我觉得后序遍历比较符合直觉,先把自己的左右子树全部反转再反转自己。

101. 对称二叉树

很多时候递归函数都是要另外写的,而不是直接用题目给的函数。

一开始想的是用两个指针遍历左右两个子树,左子树按照左中右遍历,右子树按照右中左遍历。但这样实现起来有困难,没办法用递归写。再观察其他的规律:

class Solution {
public:
    bool compare(TreeNode*left, TreeNode*right){
        if(left==nullptr&&right==nullptr) return true;
        else if((left==nullptr&&right!=nullptr)||(left!=nullptr&&right==nullptr)) return false;
        else if(left->val!=right->val) return false;
        else return compare(left->left,right->right)&&compare(left->right,right->left);
    }

    bool isSymmetric(TreeNode* root) {
        if(root==nullptr) return true;
        return compare(root->left,root->right);
    }
};

104.二叉树的最大深度

深度 vs 高度

很好理解,就是第一反应的那样

  • 二叉树节点的深度:指从根节点到该节点的最长简单路径边的条数或者节点数(取决于深度从0开始还是从1开始)
  • 二叉树节点的高度:指从该节点到叶子节点的最长简单路径边的条数或者节点数(取决于高度从0开始还是从1开始)
class Solution {
public:
    int getDep(TreeNode*root){
        if(root==nullptr) return 0;
        int dep=1+max(getDep(root->left),getDep(root->right));

        return dep;
    }

    int maxDepth(TreeNode* root) {
        return getDep(root);
    }
};

111.二叉树的最小深度

一开始想当然的认为跟上一题的代码一样,把max换成min就行了。

int leftDepth = getDepth(node->left);
int rightDepth = getDepth(node->right);
int result = 1 + min(leftDepth, rightDepth);
return result;

但这样写是有问题的。因为最小深度是从根节点到最近叶子节点的最短路径上的节点数量。直接写min的话会一直取0.

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

    int minDepth(TreeNode* root) {
        return getDep(root);
    }
};
posted @ 2025-03-30 11:10  ChloeChen0221  阅读(11)  评论(0)    收藏  举报