python - LCA between two nodes -
can code on how find least common ancestor between 2 nodes on binary search tree. did following need on question4 function. want implement efficient solution without creating tree , adding nodes it. appreciated.
here original question;
find least common ancestor between 2 nodes on binary search tree. least common ancestor farthest node root ancestor of both nodes. example, root common ancestor of nodes on tree, if both nodes descendents of root's left child, left child might lowest common ancestor. can assume both nodes in tree, , tree adheres bst properties. function definition should question4(t, r, n1, n2), t tree represented matrix, index of list equal integer stored in node , 1 represents child node, r non-negative integer representing root, , n1 , n2 non-negative integers representing 2 nodes in no particular order. example, 1 test case might be
question4([[0, 1, 0, 0, 0], > > [0, 0, 0, 0, 0], > > [0, 0, 0, 0, 0], > > [1, 0, 0, 0, 1], > > [0, 0, 0, 0, 0]], > > 3, > > 1, > > 4)
and answer 3.
thank you,
root = none class node(object): #constructor create new node def __init__(self, data): self.data = data self.left = none self.right = none def lca(r, n1, n2): while r: if n1.data < r.data > n2.data: r = r.left elif n1.data > r.data < n2.data: r = r.right else: return r def question4(t, r, n1, n2): def main(): print question4([[0, 0, 0, 0, 0], [1, 0, 1, 0, 0], [0, 0, 0, 0, 0], [0, 1, 0, 0, 1], [0, 0, 0, 0, 0]],3, 1, 2) if __name__ == '__main__':
Comments
Post a Comment