Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
For example, this binary tree is symmetric:
1 / \ 2 2 / \ / \ 3 4 4 3
But the following is not:
1 / \ 2 2 \ \ 3 3
Note:
Bonus points if you could solve it both recursively and iteratively.
confused what "{1,#,2,3}"
means? > read more on how binary tree is serialized on OJ.
判断是否是平衡树。 平衡树的定义是 左右子节点的值相等,并且其左子结点的右子结点,和右子结点的左子结点的值相等。相当拗口。 root.left.right = root.right.left 这个简洁一些。递归解法:
# Definition for a binary tree node
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# @param root, a tree node
# @return a boolean
def helper(self,m,n):
if m== None and n == None:
return True
if m and n and m.val == n.val :
return self.helper(m.right, n.left) and self.helper(m.left, n.right)
return False
def isSymmetric(self, root):
if root == None : return True
return self.helper(root.left, root.right)