Time: O(n) since we need to go through every pair of nodes to check if they have same values. Then go back to parent node to search another pair of nodes
Space: O(height of tree)
4. Coding
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
#
#
# @param root TreeNode类
# @return bool布尔型
#
class Solution:
def isSymmetric(self , root ):
# write code here
# idea
# 1. recursion
# input: two nodes
# output: boolean
# if two nodes' values are equal, use recursion to
# compare node1.left, node2.right, node1.right and node2.left
# if not equal or one of two nodes is None but the other is not->return False
#
if not root:
return True
return self.checknodes(root.left, root.right)
def checknodes(self, n1, n2):
if not n1 and not n2:
return True
if (n1 and not n2) or (n2 and not n1):
return False
if n1.val != n2.val:
return False
return self.checknodes(n1.left, n2.right) and self.checknodes(n2.left, n1.right)