LeetCode 101. Symmetric Tree

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

Description

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

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

Solution

Solution 1

40 ms AC.
如果root是对称的,那么他的左右子树对称。递归验证对称性

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    # judge whether root1 and root2 are symmetric
    def judge(self, root1, root2):
        if not root1 and not root2:     # all empty
            return True
        elif (not root1) or (not root2):    # one is empty, the other is not
            return False
        elif root1.val != root2.val:
            return False
        
        symmetric1, symmetric2 = False, False
        if not root1.left and not root2.right:      # these two are empty
            symmetric1 = True
        elif root1.left and root2.right:
            symmetric1 = self.judge(root1.left, root2.right)
        
        if not root1.right and not root2.left:      # these two are empty
            symmetric2 = True
        elif root1.right and root2.left:
            symmetric2 = self.judge(root1.right, root2.left)
        return symmetric1 and symmetric2
        
        
        
    def isSymmetric(self, root: 'TreeNode') -> 'bool':
        if not root:
            return True
        # Recursively judge whether left of root and right of root are symmetric
        return self.judge(root.left, root.right)

Solution 2

44 ms AC.
对称的必要条件:

  1. 中序遍历得到的序列应该是左右对称的 (191/193 passed)
  2. 中序遍历和逆中序遍历得到的序列应该是相同的 (192/193 passed)

用条件2做,可以达到 192/193 passed。只有一个特殊样例过不了:[5,4,1,null,1,null,4,2,null,2,null]
因为这棵树的中序和逆中序序列是完全一样的。

     5
    / \
   4   1
  / \    \
    1     4
  /      /
 2     2

特殊判断一下root的左右子树是否相等,可以AC。此做法不推荐,投机取巧之嫌,而且比法1麻烦。

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
   nodelist = []
   # 中序遍历
   # root.left, root, root.right
   def inorder(self, root):
       if not root:
           return
       
       isLeaf = False
       if not root.left and not root.right:
           isLeaf = True
       
       if root.left:
           self.inorder(root.left)
       elif not isLeaf:
           self.nodelist.append(None)
           
       self.nodelist.append(root.val)
       
       if root.right:
           self.inorder(root.right)
       elif not isLeaf:
           self.nodelist.append(None)

   # 逆中序遍历
   # root.right, root, root.left
   def reverseInorder(self, root):
       if not root:
           return
       
       isLeaf = False
       if not root.left and not root.right:
           isLeaf = True
       
       if root.right:
           self.reverseInorder(root.right)
       elif not isLeaf:
           self.nodelist.append(None)
           
       self.nodelist.append(root.val)
       
       if root.left:
           self.reverseInorder(root.left)
       elif not isLeaf:
           self.nodelist.append(None)
           
   
   def judge(self, lst1, lst2):
       len1, len2 = len(lst1), len(lst2)
       if len1 != len2:
           return False
       for i in range(len1):
           if lst1[i] != lst2[i]:
               return False
       return True

       
   def isSymmetric(self, root: 'TreeNode') -> 'bool':
       self.nodelist = []
       self.inorder(root)
       lst1 = self.nodelist.copy()
       # print(self.nodelist)
       
       self.nodelist = []
       self.reverseInorder(root)
       lst2 = self.nodelist.copy()
       # print(self.nodelist)
       
       if self.judge(lst1, lst2):
           # special judgement
           if root and root.left and root.right:
               if root.left.val != root.right.val:
                   return False
           return True
       return False

你可能感兴趣的:(LeetCode)