zoukankan      html  css  js  c++  java
  • 【LeetCode】面试题28. 对称的二叉树

    题目:

    思路:

    1、递归处理子问题,判断某个树是否对称只需要判断它的左右子树是否对称,而判读两个树是否对称需要判断: 根结点是否相等 && A.left和B.right是否对称 && A.right和B.left是否对称。判断子树是否对称变成了相同的子问题,递归处理。注意这里的核心是把一颗树是否对称的问题转换成了判断两个树是否对称,从而可以得到相同子问题并递归处理;如果像原问题那样判断一颗树是否对称无法分解成子问题,因为左子树对称并且右子树对称并不能得到该树是对称树,而是左子树和右子树对称才能得到该树对称。
    2、广度优先遍历(层次遍历),利用队列实现(双端队列或两个队列)

    代码:

    Python

    # Definition for a binary tree node.
    # class TreeNode(object):
    #     def __init__(self, x):
    #         self.val = x
    #         self.left = None
    #         self.right = None
    
    class Solution(object):
        def isMirror(self, A, B):
            if A is None and B is None:
                return True
            if A is None or B is None:
                return False
            if A.val == B.val:
                return self.isMirror(A.left, B.right) and self.isMirror(A.right, B.left)
            return False
    
        def isSymmetric(self, root):
            """
            :type root: TreeNode
            :rtype: bool
            """
            if root is None:
                return True
            return self.isMirror(root.left, root.right)
    
    # Definition for a binary tree node.
    # class TreeNode(object):
    #     def __init__(self, x):
    #         self.val = x
    #         self.left = None
    #         self.right = None
    
    class Solution(object):
        def isSymmetric(self, root):
            """
            :type root: TreeNode
            :rtype: bool
            """
            if root is None:
                return True
            A = [root.left]
            B = [root.right]
            while A:
                a = A.pop()
                b = B.pop()
                if a is None and b is None:
                    continue
                elif a is None or b is None:
                    return False
                elif a.val != b.val:
                    return False
                else:
                    A.append(a.left)
                    A.append(a.right)
                    B.append(b.right)
                    B.append(b.left)
            return True
    

    相关问题

  • 相关阅读:
    二分查找 【数组的二分查找】
    二分答案 [TJOI2007]路标设置
    队测 逆序对 permut
    【线段树】 求和
    状压DP Sgu223 骑士
    状压DP Poj3311 Hie with the Pie
    状压DP入门 传球游戏之最小总代价
    状压DP 小W选书籍
    状压DP [Usaco2008 Nov]mixup2 混乱的奶牛
    __gcd()用法
  • 原文地址:https://www.cnblogs.com/cling-cling/p/13042407.html
Copyright © 2011-2022 走看看