I am working on this question (https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/) and I tried to solve it with backtracking in python, here is my logic:
- Traverse through the tree and find both of the nodes
- return their path, and then find the first element that appears in both path and it would be the LCA
Here is my code:
class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
self.path_1 = []
self.path_2 = []
self.traverse(root, [], p, q)
print(self.path_1, self.path_2)
for val in self.path_1:
if val in self.path_2:
return val
def traverse(self, node, path, p, q):
if not node:
return
path.append(node.val)
if node is p:
self.path_1 = path
if node is q:
self.path_2 = path
self.traverse(node.left, path, p, q)
self.traverse(node.right, path, p, q)
path.remove(node.val)
It seems the backtracking part does not work and it does not give me the path to both nodes. Can someone help me troubleshoot how to fix this method? I know this solution isn't the most optimal way to solve this question, but I wanted to know what is wrong with my logical thoughts in code. Thanks upfront!