题目:
请实现一个函数,用来判断一棵二叉树是不是对称的。如果一棵二叉树和它的镜像一样,那么它是对称的。
leetcode原题链接
思路:
夭折思路:本来想先中序遍历,将结果存入数组,判断数组是否对称,觉得过于复杂了,就没有实操。
采用思路:递归。左节点的左节点 值 == 右节点的右节点 值 and 左节点的右节点值 ==右节点的左节点值
下图搬运自leetcode评论区
代码:
时间复杂度:
空间复杂度:
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def isSymmetric(self, root: TreeNode) -> bool:
def duichen(left,right):
if left is None and right is None:
return True
elif left is None or right is None:
return False
elif left.val!=right.val:
return False
else:
r1=duichen(left.left,right.right)
r2=duichen(left.right,right.left)
return r1 and r2
if root is None:#二叉树是空树,对称,返回True
return True
return duichen(root.left,root.right)#将root的左节点和右节点输入函数
错误代码:
最后一行代码,起初未加return,直接写的duichen(root.left,root.right)
导致函数isSymmetric无返回值,输出显示null
Q:函数isSymmetric()最后调用了duichen(),duichen()有返回值(True or False),调用完还是得再return一次?