[Leetcode]Symmetric Tree

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.

confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.



1. 递归方法

要保证symmetric就必须保证root的左右节点要是相同的。左右节点的所有子孙,都是其左节点的左儿子要等于右节点的又儿子,左节点的右儿子要等于右节点的左儿子,因此可以递归。

public boolean isSymmetric(TreeNode root) {
        if (root == null) {
            return true;
        }
        return isSymmetric(root.left, root.right);
    }
    private boolean isSymmetric(TreeNode lt, TreeNode rt) {
        if (lt == null && rt == null) {
            return true;
        }
        if (lt == null && rt != null || lt != null && rt == null || lt.val != rt.val) {
            return false;
        }
        return isSymmetric(lt.left, rt.right) && isSymmetric(lt.right, rt.left);
    }


2. 遍历

使用层续遍历,判断每一层是否对称即可

def isSymmetric(self, root):
        if root is None:
            return True
        q = []
        q.append(root)
        level_num = 1
        while level_num != 0:
            i = 0
            while i < level_num:
                node = q[i]
                i = i + 1
                if node is None:
                    continue
                q.append(node.left)
                q.append(node.right)
                
            start = 0
            end = level_num - 1
            while start < end:
                lt = q[start]
                rt = q[end]
                if lt is not None and rt is not None:
                    if lt.val != rt.val:
                        return False
                elif (lt is None and rt is not None) or (lt is not None and rt is None):
                    return False
                start = start + 1
                end = end - 1
            q = q[level_num: ]
            level_num = len(q)
        
        return True


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值