[101] Symmetric Tree
https://leetcode.com/problems/symmetric-tree/description/
- algorithms
- Easy (41.85%)
- Source Code: 101.symmetric-tree.py
- Total Accepted: 383.6K
- Total Submissions: 889.2K
- Testcase Example: '[1,2,2,3,4,4,3]'
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.
python
# 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 or not root.left and not root.right: return True
new_tree = self.buildTree(root)
return self.sameTree(root, new_tree)
def buildTree(self, root):
if not root: return None
new_tree = TreeNode(root.val)
new_tree.left = self.buildTree(root.right)
new_tree.right = self.buildTree(root.left)
return new_tree
def sameTree(self, root, new_tree):
if not root and not new_tree: return True
if not root and new_tree or root and not new_tree: return False
if not root.val == new_tree.val: return False
return self.sameTree(root.left, new_tree.left) and self.sameTree(root.right, new_tree.right)