二叉树的镜像
101. 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.
Solution
explanation: https://leetcode.com/articles/symmetric-tree/
# 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):
# do it iteratively
def isSymmetric(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
if not root:
return True
stk = [(root.left, root.right)]
while stk:
n1, n2 = stk.pop()
if n1 and n2 and n1.val != n2.val:
return False
elif n1 and n2:
stk += [(n1.left, n2.right), (n1.right, n2.left)]
elif n1 or n2:
return False
return True
# do it recursively
'''
def isSymmetric(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
if root == None:
return True
return self.Sym(root.left, root.right)
def Sym(self, left, right):
if left == None and right == None:
return True
if left and right and left.val == right.val:
return self.Sym(left.left, right.right) and self.Sym(left.right, right.left)
else:
return False
'''
二叉树的镜像
输入一棵二叉树,输出它的镜像。
比如,输入:
8
/ \
6 10
/ \ / \
5 7 9 11
输出:
8
/ \
10 6
/ \ / \
11 9 7 5
Solution
交换每个节点的左右子节点。
def MirrorRecursively(self, root):
if not root:
return
if not root.left and not root.right:
return
root.left, root.right = root.right, root.left
if root.left:
self.MirrorRecursively(root.left)
if root.right:
self.MirrorRecursively(root.right)