This is a leetcode question: https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/
My code is here
class CommonAncestor:
def traverse(self, root, A, B):
if not root:
return None
return self.helper(root, A, B)
def helper(self, node, A, B):
print(node)
if node:
left = self.helper(node.left, A, B)
right = self.helper(node.right, A, B)
if node.val == A or node.val == B:
return node
if left and right:
return node
elif left or right:
return left or right
else:
return None
Can someone please explain why this code doesn't work? It runs perfectly on my VS code but its unable to pass the test case. I have created the exact same tree here:
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
obj = CommonAncestor()
root = TreeNode(3)
root.left = TreeNode(5)
root.left.left = TreeNode(6)
root.left.right = TreeNode(2)
root.left.right.left = TreeNode(7)
root.left.right.right = TreeNode(4)
root.right = TreeNode(1)
root.right.left = TreeNode(0)
root.right.right = TreeNode(8)
root.right.right.left = None
root.right.right.right = None
I can't figure out if this is leetcode specific or its my code... Thanks so much in advance!
Okay figured it out... LeetCode's input type was a TreeNode while my input type was a int...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.