对称二叉树
给定一个二叉树,检查它是否是镜像对称的。
例如,二叉树 [1,2,2,3,4,4,3]
是对称的。
1
/ \
2 2
/ \ / \
3 4 4 3
1
/ \
2 2
\ \
3 3
思路1:使用层次遍历解决,如果每一层都是对称的 那么该二叉树为对称(正好先做的层次遍历,发现这里可以直接用同样思路做,把空节点用‘ ‘空格代替 以保证对称)
1 # Definition for a binary tree node. 2 # class TreeNode: 3 # def __init__(self, x): 4 # self.val = x 5 # self.left = None 6 # self.right = None 7 8 class Solution: 9 def isSymmetric(self, root: TreeNode) -> bool: 10 if root == None: 11 return True 12 layer = [root] 13 res = [] 14 while len(layer): 15 this_res = [] 16 next_l = [] 17 for n in layer: 18 if n == ‘ ‘: 19 this_res.append(‘ ‘) 20 continue 21 this_res.append(n.val) 22 if n.left: 23 next_l.append(n.left) 24 else: 25 next_l.append(‘ ‘) 26 if n.right: 27 next_l.append(n.right) 28 else: 29 next_l.append(‘ ‘) 30 for i in range(len(this_res)//2): 31 if this_res[i] != this_res[len(this_res)-i-1]: 32 return False 33 layer = next_l 34 35 return True
递归判断:
1 # Definition for a binary tree node. 2 # class TreeNode: 3 # def __init__(self, x): 4 # self.val = x 5 # self.left = None 6 # self.right = None 7 8 class Solution: 9 def judge(self, left, right): 10 if left == None and right == None: 11 return True 12 if left != None and right == None: 13 return False 14 if left == None and right != None: 15 return False 16 if left.val != right.val: 17 return False 18 return self.judge(left.right, right.left) and self.judge(left.left, right.right) 19 20 def isSymmetric(self, root: TreeNode) -> bool: 21 if root == None: 22 return True 23 return self.judge(root.left, root.right)
迭代:
def isSymmetric(self, root): if not root: return True nodeList = [root.left,root.right] while nodeList: symmetricLeft = nodeList.pop(0) symmetricRight = nodeList.pop(0) if not symmetricLeft and not symmetricRight: continue if not symmetricLeft or not symmetricRight: return False if symmetricLeft.val != symmetricRight.val: return False nodeList.append(symmetricLeft.left) nodeList.append(symmetricRight.right) nodeList.append(symmetricLeft.right) nodeList.append(symmetricRight.left) return True
LeetCode_101 对称二叉树的几种思路(Python实现)
原文:https://www.cnblogs.com/watch-fly/p/leetcode_101_watchfly.html