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

 今天都是重复的题,都还比较简单

226. 翻转二叉树

给你一棵二叉树的根节点 root ,翻转这棵二叉树,并返回其根节点。

示例 1:

输入:root = [4,2,7,1,3,6,9]
输出:[4,7,2,9,6,3,1]

示例 2:

输入:root = [2,1,3]
输出:[2,3,1]

示例 3:

输入:root = []
输出:[]

递归法简单

class Solution {
public:
    TreeNode* invertTree(TreeNode* root) {
        if(root == NULL) return root;
        swap(root->left,root->right);
        invertTree(root->left);
        invertTree(root->right);
        return root;
    }
};

101. 对称二叉树

给你一个二叉树的根节点 root , 检查它是否轴对称。

示例 1:

输入:root = [1,2,2,3,4,4,3]
输出:true

示例 2:

输入:root = [1,2,2,null,3,null,3]
输出:false

写这题差点又忘了判空的状态

class Solution {
public:
    bool order(TreeNode * a,TreeNode * b)
    {
        if(a == NULL && b != NULL) return false;
        else if(a != NULL && b == NULL) return false;
        else if(a == NULL && b == NULL) return true;//注意这个的位置,需要先判空了在判断后面的     
        else if(a->val != b->val ) return false;
        else
        {
            bool x = order(a->left,b->right);
            bool y = order(a->right,b->left);
            return x&&y;
        }
    }
    bool isSymmetric(TreeNode* root) {
        if(root == NULL) return true;
        return order(root->left,root->right);
    }
};

104. 二叉树的最大深度

给定一个二叉树 root ,返回其最大深度。

二叉树的 最大深度 是指从根节点到最远叶子节点的最长路径上的节点数。

示例 1:

输入:root = [3,9,20,null,null,15,7]
输出:3

示例 2:

输入:root = [1,null,2]
输出:2

递归法简单,层次遍历直观

class Solution {
public:
    int getDepth(TreeNode * cur,int &depth)
    {
        if(cur == NULL) return 0;
        int leftdepth = getDepth(cur->left,depth);
        int rightdepth = getDepth(cur->right,depth);
        depth = 1 + max(leftdepth,rightdepth);
        return depth;
    }


    int maxDepth(TreeNode* root) {
        int depth = 0;
        return getDepth(root,depth);
    }
};

111. 二叉树的最小深度

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

最小深度是从根节点到最近叶子节点的最短路径上的节点数量。

说明:叶子节点是指没有子节点的节点。

示例 1:

输入:root = [3,9,20,null,null,15,7]
输出:2

示例 2:

输入:root = [2,null,3,null,4,null,5,null,6]
输出:5

小心不要犯经典错误

class Solution {
public:
    int getDepth(TreeNode * cur,int &depth)
    {
        if(cur == NULL) return 0;
        int leftdepth = getDepth(cur->left,depth);
        int rightdepth = getDepth(cur->right,depth);
//        depth = 1 + min(leftdepth,rightdepth);经典的错误,标准的零分
        if(cur->left == NULL && cur->right != NULL) return (1 + rightdepth);
        if(cur->right == NULL && cur->left != NULL) return (1 + leftdepth);
        depth = 1 + min(leftdepth,rightdepth);
        return depth;
    }


    int minDepth(TreeNode* root) {
        int depth = 0;
        return getDepth(root,depth);
    }
};

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值