【剑指offer】58 对称的二叉树

题目

在这里插入图片描述

分析

非递归的方法,每一层判断是不是回文序列
递归的方法
left.val == right.val 同时
left.left.val == right.right.val 同时
left.right.val == left.left.val
满足这三个条件

python代码

非递归

# -*- coding:utf-8 -*-
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
class Solution:
    def isSymmetrical(self, pRoot):
        # write code here
        if not pRoot: return True
        arr = [pRoot]
        
        while len(arr)!=0:
            temp_arr = []
            temp_res = []
            for n in arr:
                if n.val!="#":
                    temp_res.append(n.val)
                    if n.left:
                        temp_arr.append(n.left)
                    else:
                        temp_arr.append(TreeNode("#"))
                    if n.right:
                        temp_arr.append(n.right)
                    else:
                        temp_arr.append(TreeNode("#"))
                else:
                    temp_res.append("#")
            for i in range(len(temp_arr)/2):
                if temp_res[i] == temp_res[-(i+1)]:
                    pass
                else:
                    return False
            arr = temp_arr
        return True

递归

class Solution:
    def isSymmetrical(self, pRoot):
        # write code here
        
        return self.isSame(pRoot, pRoot)
    def isSame(self,root1,root2):
        if not root1 and not root2: return True
        if not root1 or not root2: return False
        return (root1.val == root2.val) and self.isSame(root1.left,root2.right) and self.isSame(root1.right,root2.left)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值