0

I want to convert Binary Tree into Array using Python and i don't know how to give index to tree-node?

I have done this using the formula left_son=(2*p)+1; and right_son=(2*p)+2; in java But i'm stuck in python. Is there any Function to give index to tree-node in python ?

0

2 Answers 2

8

You can represent a binary tree in python as a one-dimensional list the exact same way.

For example if you have at tree represented as:

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 14, 15]

0 is the root
1 & 2 are the next level
the children of 1 & 2 are [3, 4] and [5, 6]

This corresponds to your formula. For a given node at index i the children of that node are (2*i)+1 (2*i)+2. This is a common way to model a heap. You can read more about how Python uses this in its [heapq library].(https://docs.python.org/3.0/library/heapq.html)

You can use this to traverse the tree in depths with something like:

a =  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 14, 15]

def childNodes(i):
     return (2*i)+1, (2*i)+2

def traversed(a, i=0, d = 0):
    if i >= len(a):
        return 
    l, r =  childNodes(i)
    traversed(a, r, d = d+1)
    print("   "*d + str(a[i]))
    traversed(a, l, d = d+1)

traversed(a)

This Prints

         15
      6
         14
   2
         13
      5
         11
0
         10
      4
         9
   1
         8
      3
         7
Sign up to request clarification or add additional context in comments.

5 Comments

is this what OP has asked about? It is about convert Binary Tree into Array using Python. Why is there a need to traverse tree in depths?
@taurus05 The formulas the op is referencing at those used in representing trees as arrays which is a common comp science exercise and is useful in a lot of contexts. I see the word represent not covert in the title. Or course I could be wrong.
you're right! title says represent, whereas body has convert. The question is not clear in that sense.
Maybe both answers will be useful.
you're right! Both of the answers aree useful then.
1

Incase of a binary tree, you'll have to perform a level order traversal. And as you keep traversing, you'll have to store the values in the array in the order they appear during the traversal. This will help you in restoring the properties of a binary tree and will also maintain the order of elements. Here is the code to perform level order traversal.

class Node: 

    # A utility function to create a new node 
    def __init__(self, key): 
        self.data = key  
        self.left = None
        self.right = None


# Function to  print level order traversal of tree 
def printLevelOrder(root): 
    h = height(root) 
    for i in range(1, h+1): 
        printGivenLevel(root, i) 


# Print nodes at a given level 
def printGivenLevel(root , level): 
    if root is None: 
        return
    if level == 1: 
        print "%d" %(root.data), 
    elif level > 1 : 
        printGivenLevel(root.left , level-1) 
        printGivenLevel(root.right , level-1) 


""" Compute the height of a tree--the number of nodes 
    along the longest path from the root node down to 
    the farthest leaf node 
"""
def height(node): 
    if node is None: 
        return 0 
    else : 
        # Compute the height of each subtree  
        lheight = height(node.left) 
        rheight = height(node.right) 

        #Use the larger one 
        if lheight > rheight : 
            return lheight+1
        else: 
            return rheight+1

# Driver program to test above function 
root = Node(1) 
root.left = Node(2) 
root.right = Node(3) 
root.left.left = Node(4) 
root.left.right = Node(5) 

print "Level order traversal of binary tree is -"
printLevelOrder(root)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.