[LeeCode] 101. Symmetric Tree (递归) 平衡二叉树

101. Symmetric Tree

Easy

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

For example, this binary tree [1,2,2,3,4,4,3] is symmetric:

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

 

But the following [1,2,2,null,3,null,3] is not:

    1
   / \
  2   2
   \   \
   3    3

 

Follow up: Solve it both recursively and iteratively.

 

笔记:

判断是不是平衡二叉树,假设有两个节点n1,n2,如果n1的左子节点等于n2的右子节点,n1的右子节点等于n2的左子节点,那么n1,n2平衡。一直递归下去,比较完所有的节点。

方法1:递归

class Solution:
    def isSymmetric(self, root: TreeNode) -> bool:
        if root is None:
            return True

        def _sym(left_node: TreeNode, right_node: TreeNode) -> bool:
            if left_node is None and right_node is None:
                return True
            if left_node is None or right_node is None or left_node.val != right_node.val:
                return False
            return _sym(left_node.left, right_node.right) and _sym(left_node.right, right_node.left)

        return _sym(root.left, root.right)

方法2:迭代

class Solution:
    def isSymmetric(self, root: TreeNode) -> bool:
        if root is None:
            return True
        s1, s2 = [root.left], [root.right]
        while s1 and s2:
            s1_node, s2_node = s1.pop(), s2.pop()
            if s1_node is None and s2_node is None:
                continue
            if (s1_node is None and s2_node) or (s1_node and s2_node is None) or s1_node.val != s2_node.val:
                return False
            s1.append(s1_node.left)
            s2.append(s2_node.right)
            s1.append(s1_node.right)
            s2.append(s2_node.left)
        return True

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值