chengchengxu15 / CS-leaning

1 stars 1 forks source link

101. Symmetric Tree #40

Closed chengchengxu15 closed 3 years ago

chengchengxu15 commented 3 years ago

Given the root of a binary tree, check whether it is a mirror of itself (i.e., symmetric around its center).

https://leetcode.com/problems/symmetric-tree/

chengchengxu15 commented 3 years ago

my solution 用 102, 层次遍历的方法去读取左右树,看是否每层的val对称。

class Solution:
    def isSymmetric(self, root: Optional[TreeNode]) -> bool:
        if not root:
            return False
        if not root.left or not root.right:
            if root.left == root.right:
                return True
            else:
                return False

        list_left_root = [root.left]
        list_right_root = [root.right]

        while list_left_root and list_right_root:
            if len(list_left_root) != len(list_right_root):
                return False
            left_tmp_root =[]
            right_tmp_root =[]

            for i in range(len(list_left_root)):

                if not list_left_root[i] or not list_right_root[i]:
                    if list_left_root[i] != list_right_root[i]:
                        return False

                elif list_left_root[i] and list_right_root[i] and list_left_root[i].val != list_right_root[i].val:
                    return False

                else:
                    left_tmp_root.append(list_left_root[i].left)
                    right_tmp_root.append(list_right_root[i].right)
                    left_tmp_root.append(list_left_root[i].right)
                    right_tmp_root.append(list_right_root[i].left)

            list_left_root = left_tmp_root
            list_right_root = right_tmp_root

        return True
chengchengxu15 commented 3 years ago

https://leetcode-cn.com/problems/symmetric-tree/solution/dui-cheng-er-cha-shu-by-leetcode-solution/ recursion:

class Solution(object):
    def sym(self, L,R):
        if not L and not R:
            return True
        elif not L or not R:
            return False
        else:
            if L.val!=R.val:
                return False
            else:
                return self.sym(L.left,R.right) and self.sym(L.right,R.left)
    def isSymmetric(self, root):
        """
        :type root: TreeNode
        :rtype: bool
        """
        def sym(L,R):
            if not L and not R:
                return True
            elif not L or not R:
                return False
            else:
                if L.val!=R.val:
                    return False
                else:
                    return sym(L.left,R.right) and sym(L.right,R.left)
        if not root:
            return True
        else:
            return sym(root.left, root.right)