Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit f3371a9

Browse files
committedJun 21, 2017
Construct tree from its Inorder and Preorder
1 parent 18022dc commit f3371a9

File tree

1 file changed

+69
-0
lines changed

1 file changed

+69
-0
lines changed
 
Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
# Python program to construct tree using inorder and
2+
# preorder traversals
3+
4+
# A binary tree node
5+
class Node:
6+
7+
# Constructor to create a new node
8+
def __init__(self, data):
9+
self.data = data
10+
self.left = None
11+
self.right = None
12+
13+
"""Recursive function to construct binary of size len from
14+
Inorder traversal in[] and Preorder traversal pre[]. Initial values
15+
of start and end should be 0 and len -1. The function doesn't
16+
do any error checking for cases where inorder and preorder
17+
do not form a tree """
18+
def buildTree(inOrder, preOrder, start, end):
19+
if (start > end):
20+
return None
21+
22+
# Pick current node from Preorder traversal using
23+
# preIndex and increment preIndex
24+
tNode = Node(preOrder[buildTree.preIndex])
25+
buildTree.preIndex += 1
26+
27+
# If this node has no children then return
28+
if start == end :
29+
return tNode
30+
31+
# Else find the index of this node in Inorder traversal
32+
rootIndex = search(inOrder, start, end, tNode.data)
33+
34+
# Using index in Inorder Traversal, construct left
35+
# and right subtrees
36+
tNode.left = buildTree(inOrder, preOrder, start, rootIndex-1)
37+
tNode.right = buildTree(inOrder, preOrder, rootIndex+1, end)
38+
39+
return tNode
40+
41+
# function to search for the index
42+
def search(arr, start, end, value):
43+
for i in range(start, end+1):
44+
if arr[i] == value:
45+
return i
46+
47+
# function to print the contents of the tree in inorder fashion
48+
def inorder(node):
49+
if node is None:
50+
return
51+
52+
# first recur on left child
53+
inorder(node.left)
54+
#then print the data of node
55+
print (node.data, end = ' ')
56+
# now recur on right child
57+
inorder(node.right)
58+
59+
# Driver program to test above function
60+
inOrder = ['D', 'B' ,'E', 'A', 'F', 'C']
61+
preOrder = ['A', 'B', 'D', 'E', 'C', 'F']
62+
63+
# Static variable preIndex
64+
buildTree.preIndex = 0
65+
root = buildTree(inOrder, preOrder, 0, len(inOrder)-1)
66+
67+
# Let us test the build tree by priting Inorder traversal
68+
print ("Inorder traversal of the constructed tree is")
69+
inorder(root)

0 commit comments

Comments
 (0)
Please sign in to comment.