How to find position of nodes in binary tree?

Viewed 1814
4 0 2
0 1
0 3
2 3
0
3

I'm trying to find effective solution to the above problem.

Given input first line is: number of nodes in binary tree=4, root=0, depths=2

Edges or nodes on the edge are not given in any specific order, but edge that connects node to left child appears in input.

and the last two lines to find the position of 0 and 3 ,its output is

 1 2
 3 1

Tree can have more than million nodes and build tree using

I couldn't find how to represent tree in such way that it would be possible to find coordinates of nodes

updated code

class node:
    def __init__(self, x):
        self.x=4
        self.l=2
        self.r=0
        self.id=id


    def recurse(node,id, depth = -1, position=-1, max_depth=-1):
        depth=depth+1
        current_depth=depth
        max_depth=max(max_depth,current_depth)

        matchl=False
        matchr=False

        if node.l :
            (depthl,position,max_depth,matchl)=node.recurse(node.l,id,current_depth,position,max_depth)

        positionl = position
        position = position + 1
        current_position=position


        if node.r:
            (depth,position,max_depth,matchr)=node.recurse(node.r,id,current_depth,position,max_depth)

        if matchl:
            return (depthl,positionl,max_depth,True)

        if node.x==id:
            return (current_depth,current_position,max_depth,True)
        return (depth,position,max_depth,matchr)


n2=node(2)
n3=node(3)
n1=node(1)
n0=node(0)

n0.l=n1
n0.r=n3
n3.l=n2

(depth,position,max_depth,match)=node.recurse(n0,3)
if match:
   answer = (position, max_depth - depth )
2 Answers
Related