- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Program to generate tree using preorder and inorder traversal in python
Suppose we have the preorder and inorder traversal of a binary tree. We have to recover the tree from these sequences. So if the preorder and inorder sequences are [3,9,20,15,7] and [9,3,15,20,7], then the tree will be:
Let us see the steps:
- Define a method called buildTree(), this will the preorder and inorder traversal sequences.
- if inorder traversal list is not empty, then
- root := create a tree node with value same first element from preorder sequence, and remove first item from preorder traversal
- root_index := index of value of root in inorder list
- left of root := buildTree(preorder, inorder[from index 0 to root_index])
- right of root := buildTree(preorder, inorder[from index root_index+1 to end])
- return root
Let us see the following implementation to get better understanding:
Example
class TreeNode: def __init__(self, data, left = None, right = None): self.data = data self.left = left self.right = right def print_tree(root): if root is not None: print_tree(root.left) print(root.data, end = ',') print_tree(root.right) class Solution(object): def buildTree(self, preorder, inorder): if inorder: root = TreeNode(preorder.pop(0)) root_index = inorder.index(root.data) root.left = self.buildTree(preorder,inorder[:root_index]) root.right = self.buildTree(preorder,inorder[root_index+1:]) return root ob1 = Solution() print_tree(ob1.buildTree([3,9,20,15,7], [9,3,15,20,7]))
Input
[3,9,20,15,7],[9,3,15,20,7]
Output
9,3,15,20,7,
Advertisements