二叉树 06. 对称二叉树
方法一:递归 时间复杂度O(N) 空间复杂度O(N)
def isSymmetric(root): """ :type root: TreeNode :rtype: bool """ def sym(l,r): if not l and not r: return True if l and r and l.val == r.val: return sym(l.left,r.right) and sym(l.right,r.left) return False return sym(root.left,root.right)
方法二:队列 时间复杂度O(N) 空间复杂度O(N) 成对进出
def isSymmetric(root): """ :type root: TreeNode :rtype: bool """ if root is None: return True queue = [] queue.append(root.left) queue.append(root.right) while queue != []: l = queue.pop(0) r = queue.pop(0) if l is None and r is None: continue if (l is None) ^ (r is None): return False if l and r and l.val != r.val: return False queue.append(l.left) queue.append(r.right) queue.append(l.right) queue.append(r.left) return True

浙公网安备 33010602011771号