leetcode 101.对称的二叉树(python)
给定一个二叉树,检查它是否是镜像对称的。
例如,二叉树 [1,2,2,3,4,4,3] 是对称的。
1
/ \
2 2
/ \ / \
3 4 4 3
但是下面这个 [1,2,2,null,3,null,3] 则不是镜像对称的:
1
/ \
2 2
\ \
3 3
进阶:
你可以运用递归和迭代两种方法解决这个问题吗?
递归
class Solution(object):
def isSymmetric(self
, root
):
if not root
:
return True
return self
.dfs
(root
.left
, root
.right
)
def dfs(self
, l
, r
):
if l
and r
:
return l
.val
== r
.val
and self
.dfs
(l
.left
, r
.right
) and self
.dfs
(r
.left
, l
.right
)
return l
== r
迭代
class Solution(object):
def isSymmetric(self
, root
):
if not root
:
return True
stack
= [(root
.left
, root
.right
)]
while stack
:
l
, r
= stack
.pop
()
if not l
and not r
:
continue
if not l
or not r
or l
.val
!= r
.val
:
return False
stack
.append
((l
.left
, r
.right
))
stack
.append
((l
.right
, r
.left
))
return True