Leecode刷题之旅-C语言/python-101对称二叉树

/*
 * @lc app=leetcode.cn id=101 lang=c
 *
 * [101] 对称二叉树
 *
 * https://leetcode-cn.com/problems/symmetric-tree/description/
 *
 * algorithms
 * Easy (45.30%)
 * Total Accepted:    23.8K
 * Total Submissions: 52.4K
 * Testcase Example:  '[1,2,2,3,4,4,3]'
 *
 * 给定一个二叉树,检查它是否是镜像对称的。
 * 
 * 例如,二叉树 [1,2,2,3,4,4,3] 是对称的。
 *  
 * 
 * ⁠   1
 * ⁠  / \
 * ⁠ 2   2
 * ⁠/ \ / \
 * 3  4 4  3
 * 
 * 
 * 但是下面这个 [1,2,2,null,3,null,3] 则不是镜像对称的:
 * 
 * ⁠   1
 * ⁠  / \
 * ⁠ 2   2
 * ⁠  \   \
 * ⁠  3    3
 * 
 * 
 * 说明:
 * 
 * 如果你可以运用递归和迭代两种方法解决这个问题,会很加分。
 * 
 */
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */
bool com(struct TreeNode* a,struct TreeNode* b);

bool isSymmetric(struct TreeNode* root) {

    if(root == NULL)

        return true;

    return com(root->left,root->right);
}
bool com(struct TreeNode* a,struct TreeNode* b)
{
    if(a == NULL&&b == NULL)
        return true;
    else
    {
        if(a == NULL||b == NULL)
            return false;
        else if(a -> val==b -> val)
            return com(a->left,b->right)&&com(a->right,b->left);
        else
            return false;
    }      
}

这里应用递归算法。需要引用一个自己创建的函数(只有一个root是无法递归出来的)

其实有点像前一道相同的树那道题,这里判断的对称的本质就是 左子树的右子树等于右子树的左子树 就是对称。

----------------------------------------------------------------------------------------------------------------------------------------------------

python:

#
# @lc app=leetcode.cn id=101 lang=python3
#
# [101] 对称二叉树
#
# https://leetcode-cn.com/problems/symmetric-tree/description/
#
# algorithms
# Easy (45.30%)
# Total Accepted:    23.8K
# Total Submissions: 52.4K
# Testcase Example:  '[1,2,2,3,4,4,3]'
#
# 给定一个二叉树,检查它是否是镜像对称的。
# 
# 例如,二叉树 [1,2,2,3,4,4,3] 是对称的。
# 
# ⁠   1
# ⁠  / \
# ⁠ 2   2
# ⁠/ \ / \
# 3  4 4  3
# 
# 
# 但是下面这个 [1,2,2,null,3,null,3] 则不是镜像对称的:
# 
# ⁠   1
# ⁠  / \
# ⁠ 2   2
# ⁠  \   \
# ⁠  3    3
# 
# 
# 说明:
# 
# 如果你可以运用递归和迭代两种方法解决这个问题,会很加分。
# 
#
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
class Solution:
    def isSymmetric(self, root):
        if root == None:
            return True
        else:
            return self.isSym(root.left, root.right)
        
    def isSym(self, p, q):
        if p == None and q == None:
            return True
        elif p == None or q == None:
            return False
        elif p.val == q.val:
            return self.isSym(p.left, q.right) and self.isSym(p.right, q.left)
        else:
            return False  

猜你喜欢

转载自www.cnblogs.com/lixiaoyao123/p/10523377.html