Note that there are some explanatory texts on larger screens.

plurals
  1. POBinary tree: first common ancestor
    primarykey
    data
    text
    <p>I have been struggling with trees and python in the last couple of days. Mostly, it's the recursion in trees that is giving me trouble. The problem that I am trying to solve is to find first common ancestor in a <em>binary tree</em>. There are plenty of solutions around that claim to have done that, but they are all for binary search trees, not binary trees. In the case of binary trees, nodes are not ordered so that left is smaller than right. I know which approach I should use, but I am failing in the recursion part: (EDIT: the problem states that I can't use additional data structures or storage)</p> <pre><code>class Node: """docstring for Node""" def __init__(self, data): self.data = data self.left=None self.right=None def findNode(self,target): if self==None: return 0 if self.data==target: return 1 return self.findNode(self.left,target) or self.findNode(self.right,target) def firstCommonAncestor(self,p,q): if self==None: return 0 if self.left.data==p and self.right.data==q: return self.data if findNode(self.left,p) and findNode(self.right,q): return 1 root=Node(2) root.left=Node(5) root.right=Node(4) root.left.left=Node(9) root.left.right=Node(7) print firstCommonAncestor(root,9,7) </code></pre> <p>I edited the code to make the problem more clear. findNode(self.left,p) and findNode(self.right,q) should return 1 since both nodes exist. However, when findNode(self.right,q) is not starting the search from the root. I know I should implement recursive calls, but everything I have tried has failed. If someone could provide some pointers on what I am doing wrong, it would be greatly appreciated! (the firstCommonAncestor is not yet implemented, so that doesn't really matter. It's not doing much for now). Edit: this is a problem from Cracking the coding interview.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload