代码随想录算法训练营第十四天| 226.翻转二叉树、101. 对称二叉树、104.二叉树的最大深度、

Leetcode 226.翻转二叉树

题目链接:226. 翻转二叉树

C++:(前序遍历)

class Solution {
public:
    TreeNode* invertTree(TreeNode* root) {
        //前序遍历
        if(root == nullptr) return root;
        swap(root->left, root->right);
        invertTree(root->left);
        invertTree(root->right);
        return root;
    }
};

Python:(中序遍历)

class Solution:
    def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
        if root == None:
            return root
        self.invertTree(root.left)
        root.left, root.right = root.right, root.left
        self.invertTree(root.left)
        return root

Leetcode101. 对称二叉树

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

C++:(后序遍历)

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 == nullptr) return true;
        return compare(root->left, root->right);
    }
};

Leetcode104.二叉树的最大深度

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

C++:(后序遍历)

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

Leetcode111.二叉树的最小深度

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

C++:(后序遍历)

class Solution {
public:
    int minDepth(TreeNode* root) {
        if(root == nullptr) return 0;
        int leftdepth = minDepth(root->left);
        int rightdepth = minDepth(root->right);
        if(root->left == nullptr && root->right != nullptr)
            return 1 + rightdepth;
        if(root->left != nullptr && root->right == nullptr)
            return 1 + leftdepth;
        int depth = 1 + min(leftdepth, rightdepth);
        return depth;
    }
};
  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值