[Leetcode]Symmetric Tree

22 篇文章 0 订阅

Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).

For example, this binary tree is symmetric:

    1
   / \
  2   2
 / \ / \
3  4 4  3

But the following is not:

    1
   / \
  2   2
   \   \
   3    3

Note:

Bonus points if you could solve it both recursively and iteratively.

判断数是否对称~不对称的条件有以下三个:(1)左边为空而右边不为空;(2)左边不为空而右边为空;(3)左边值不等于右边值~算法的时间复杂度是树的遍历O(n),空间复杂度同样与树遍历相同是O(logn)~  (写关于树的题目还是不太熟练,还得加强练习)递归代码如下~

class Solution:
    # @param root, a tree node
    # @return a boolean
    def isSymmetric(self, root):
        if root is None: return True
        return self.helper(root.left, root.right)
    
    def helper(self, root1, root2):
        if root1 is None and root2 is None: return True
        if root1 is None or root2 is None: return False
        if root1.val != root2.val: return False
        return self.helper(root1.left, root2.right) and self.helper(root1.right, root2.left)

参考了别人的代码,非递归解法如下~ (非递归解法要自己写还真是有点写不出来,加油吧~)

class Solution:
    # @param root, a tree node
    # @return a boolean
    def isSymmetric(self, root):
        if root is None: return True
        queue = [[root.left, root.right]]
        while queue:
            pair = queue.pop(0)
            if not (pair[0] or pair[1]):
                continue
            elif (pair[0] and pair[1]) and pair[0].val == pair[1].val:
                queue.append([pair[0].left, pair[1].right])
                queue.append([pair[0].right, pair[1].left])
            else:
                return False
        return True


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值