class Solution(object):
def inorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
q=[]
ret=[]
p=root
while p or q:
while p:
q.append(p)
p=p.left
p=q.pop()
ret.append(p.val)
p=p.right
return ret
# 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 preorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
if not root:
return []
stack=[root]
ret=[]
while stack:
node=stack.pop()
ret.append(node.val)
if node.right:
stack.append(node.right)
if node.left:
stack.append(node.left)
return ret
# 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 postorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
if not root:
return []
s=[root]
ret=[]
while s:
node=s.pop()
ret.insert(0,node.val) #reverse pre-order tranverse
if node.left:
s.append(node.left)
if node.right:
s.append(node.right)
return ret
class Solution(object):
def isSubtree(self, s, t):
"""
:type s: TreeNode
:type t: TreeNode
:rtype: bool
"""
if not s and not t:
return True
if t and not s:
return False
if not t and s:
return False
if s.val!=t.val:
return self.isSubtree(s.right,t) or self.isSubtree(s.left,t)
else:
return (self.isSubtree(s.left,t.left) and self.isSubtree(s.right,t.right)) or (self.isSubtree(s.right,t) or self.isSubtree(s.left,t))
Wrong Answer
× 174/176 cases passed (N/A)
× testcase: ‘[3,4,5,1,null,2]\n[3,1,2]’
× answer: true
× expected_answer: false
× stdout:
below is the right solution:
class Solution(object):
def isSubtree(self, s, t):
"""
:type s: TreeNode
:type t: TreeNode
:rtype: bool
"""
def issame(s,t):
if not s and not t:
return True
if not s or not t:
return False
if s.val!=t.val:
return False
return issame(s.left,t.left) and issame(s.right,t.right)
if not s:
return False
if issame(s,t):
return True
return isSubtree(s.left,t) or isSubtree(s.right,t)