Wednesday, July 26, 2017

[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 [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.
Whenever seeing a tree problem, always try to think recursively. However, this problem is not that easy to think a recursive solution. Why? Because, recursion usually comes like a DFS flavor, but here somehow we need to compare level-wisely. My original idea is to do a BFS, recording each level to a list and see if the list is palindrome. I think I still need to digest the following idea a little bit.


# 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 not root:
            return True
        return self.helper(root.left, root.right)
    
    def helper(self, node1, node2):
        if not node1 and not node2:
            return True
        if (not node1 and node2) or (not node2 and node1):
            return False
        if node1.val != node2.val:
            return False
        return self.helper(node1.left, node2.right) and self.helper(node1.right, node2.left)


No comments:

Post a Comment