defisSymmetricRec(self,left,right): """ :type left: TreeNode :type right: TreeNode :rtype: bool """ if left isNoneand right isNone: returnTrue elif left isnotNoneand right isnotNone: return left.val == right.val \ and self.isSymmetricRec(left.left,right.right) \ and self.isSymmetricRec(left.right,right.left) else: returnFalse
whilenot leftqueue.empty(): left = leftqueue.get() right = rightqueue.get() if left isNoneand right isNone: continue elif left isnotNoneand right isnotNone: if left.val != right.val: returnFalse leftqueue.put(left.left) leftqueue.put(left.right) rightqueue.put(right.right) rightqueue.put(right.left) else: returnFalse returnTrue
然后是在dicuss中看到的c++解法,思路其实是一样的:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
boolisSymmetric(TreeNode *root){ if (!root) returntrue; return helper(root->left, root->right); }