# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def check_sym(self, nodes): if len(nodes) <= 1: return True head = 0 tail = len(nodes)-1 while(head < tail): if nodes[head] == None and nodes[tail] == None: head += 1 tail -= 1 elif nodes[head] != None and nodes[tail] == None or nodes[head] == None and nodes[tail] != None: return False elif nodes[head].val != nodes[tail].val: return False else: head += 1 tail -= 1 return True def next_level_nodes(self, nodes): next_level = [] while nodes: node = nodes.pop() if node != None: next_level = [node.left , node.right] + next_level return next_level def isSymmetric(self, root): """ :type root: TreeNode :rtype: bool """ if root == None: return True else: nodes_same_level = [root] while len(nodes_same_level)> 0: if self.check_sym(nodes_same_level): nodes_same_level = self.next_level_nodes(nodes_same_level) else: return False return True # recursively def isMirror(self, left, right): if left == None and right == None: return True elif left == None or right == None: return False else: if left.val == right.val: return self.isMirror(left.left ,right.right) and self.isMirror(left.right , right,left) else: return False def isSymmetric2(self, root): if root == None: return True else: return self.isMirror(root.left ,root.right)
Run
Reset
Share
Import
Link
Embed
Language▼
English
中文
Python Fiddle
Python Cloud IDE
Follow @python_fiddle
Browser Version Not Supported
Due to Python Fiddle's reliance on advanced JavaScript techniques, older browsers might have problems running it correctly. Please download the latest version of your favourite browser.
Chrome 10+
Firefox 4+
Safari 5+
IE 10+
Let me try anyway!
url:
Go
Python Snippet
Stackoverflow Question