
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Construct a Binary Tree from Postorder and Inorder in Python
Suppose we have the inorder and postorder traversal sequence of a binary tree. We have to generate the tree from these sequences. So if the postorder and inorder sequences are [9,15,7,20,3] and [9,3,15,20,7], then the tree will be −
Let us see the steps −
Define a method build_tree(), this will take inorder, postorder −
If inorder list is not empty −
root := make a tree node with the last value of postorder, then delete that element
ind := index of root data in inorder list
right of root := build_tree(inorder from index ind to end, postorder)
left of root := build_tree(inorder from 0 to index ind - 1, postorder)
return root
Example
Let us see the following implementation to get better understanding −
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, inorder, postorder): if inorder: root = TreeNode(postorder.pop()) ind = inorder.index(root.data) root.right = self.buildTree(inorder[ind+1:],postorder) root.left = self.buildTree(inorder[:ind],postorder) return root ob1 = Solution() print_tree(ob1.buildTree([9,3,15,20,7], [9,15,7,20,3]))
Input
[9,3,15,20,7] [9,15,7,20,3]
Output
[9,3,15,20,7]
- Related Articles
- Construct Binary Tree from Inorder and Postorder Traversal in Python
- Construct Binary Tree from Preorder and Postorder Traversal in Python
- Construct a Binary Search Tree from given postorder in Python
- Construct Binary Tree from Preorder and Inorder Traversal in Python
- Construct Special Binary Tree from given Inorder traversal in C++
- Python Program to Build Binary Tree if Inorder or Postorder Traversal as Input
- Binary Tree Postorder Traversal in Python
- Binary Tree Inorder Traversal in Python
- Construct String from Binary Tree in Python
- Binary Tree Postorder Traversal in Python Programming
- Construct Tree from given Inorder and Preorder traversals in C++
- Preorder from Inorder and Postorder traversals in C++
- Construct Binary Search Tree from Preorder Traversal in Python
- Print Postorder traversal from given Inorder and Preorder traversals
- Construct Binary Tree from String in C++

Advertisements