给你一个二叉树的根节点 root , 检查它是否轴对称。
示例 1:
输入:root = [1,2,2,3,4,4,3]
输出:true
示例 2:
输入:root = [1,2,2,null,3,null,3]
输出:false
提示:
树中节点数目在范围 [1, 1000] 内 -100 <= Node.val <= 100
进阶:你可以运用递归和迭代两种方法解决这个问题吗?
递归法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
|
class Solution: def isSymmetric(self, root: Optional[TreeNode]) -> bool: def helper(p, q): if not p and not q: return True if not p or not q: return False return p.val == q.val and helper(p.left, q.right) and helper(p.right, q.left)
if not root: return True return helper(root.left, root.right)
|
广度优先遍历-队列
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
|
class Solution: def isSymmetric(self, root: Optional[TreeNode]) -> bool: import queue if not root: return True q = queue.Queue() q.put(root.left) q.put(root.right) while q.qsize(): l = q.get() r = q.get() if not l and not r: continue if not l or not r: return False if l.val != r.val: return False q.put(l.left) q.put(r.right) q.put(l.right) q.put(r.left) return True
|