[Python]
Construct Tree Using Inorder and Preorder
Given Preorder and Inorder traversal of a binary tree, create the binary tree associated with the traversals.You just need to construct the tree and return the root.
Note: Assume binary tree contains only unique elements.
Input format :
Line 1 : n (Total number of nodes in binary tree)
Line 2 : Pre order traversal
Line 3 : Inorder Traversal
Output Format :
Elements are printed level wise, each level in new line (separated by space).
Sample Input :
12 1 2 3 4 15 5 6 7 8 10 9 12 4 15 3 2 5 1 6 10 8 7 9 12
Sample Output :
1 2 6 3 5 7 4 8 9 15 10 12
Solution:
import queue
class BinaryTreeNode:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def buildTreePreOrder(preorder, inorder):
# Given Preorder and Inorder traversal of a binary tree, create the
binary
# tree associated with the traversals.You just need to construct
the tree
# and return the root. For 12 Nodes with following input:
# preOrder: 1 2 3 4 15 5 6 7 8 10 9 12
# inOrder: 4 15 3 2 5 1 6 10 8 7 9 12
#############################
# PLEASE ADD YOUR CODE HERE #
#############################
pass
def printLevelATNewLine(root):
# Given a binary tree, print the level order traversal. Make sure
each level
# start in new line.
if root==None:
return
inputQ = queue.Queue()
outputQ = queue.Queue()
inputQ.put(root)
while not inputQ.empty():
while not inputQ.empty():
curr = inputQ.get()
print(curr.data, end=' ')
if curr.left!=None:
outputQ.put(curr.left)
if curr.right!=None:
outputQ.put(curr.right)
print()
inputQ, outputQ = outputQ, inputQ
# Main
n=int(input())
preorder = [int(i) for i in input().strip().split()]
inorder = [int(i) for i in input().strip().split()]
root = buildTreePreOrder(preorder, inorder)
printLevelATNewLine(root)
Code looks like this in editor:
![In [ ]: import queue class Binary TreeNode: definit__(self, data): self.data = data self.left = None self.right = None def bu](http://img.homeworklib.com/questions/3dbe47c0-caf3-11ea-9822-6d44d605c574.png?x-oss-process=image/resize,w_560)
def ConstructTree(inOrder, preOrder, inStrt, inEnd):
if (inStrt > inEnd) :
return None
CurrentNode = Node(preOrder[ConstructTree.preIndex])
ConstructTree.preIndex += 1
if inStrt == inEnd :
return CurrentNode
inIndex = search(inOrder, inStrt, inEnd, tNode.data)
CurrentNode.left = ConstructTree(inOrder, preOrder, inStrt, inIndex-1)
CurrentNode.right = ConstructTree(inOrder, preOrder, inIndex + 1, inEnd)
return currentNode
Hope this code helps you. For better Understanding try to dry run. Please give an upvote if it does.
[Python] Construct Tree Using Inorder and Preorder Given Preorder and Inorder traversal of a binary tree,...
Previous code:
class BinarySearchTree:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def search(self, find_data):
if self.data == find_data:
return self
elif find_data < self.data and self.left != None:
return self.left.search(find_data)
elif find_data > self.data and self.right != None:
return self.right.search(find_data)
else:
return None
def get_left(self):
return self.left
def get_right(self):
return self.right
def set_left(self, tree):
self.left = tree
def set_right(self, tree):
self.right = tree
def set_data(self, data):
self.data = data
def get_data(self):
return self.data
def traverse(root,order):...
python pls and noticed the output added ""
One way to represent a binary tree is using the nested list format Consider the following binary tree: 24 72 78 8 51 25 This binary tree could be represented using a nested list as follows [55, [24, [8, None, None], [51, [25, None, None], None]], [72, None, [78, None, None ]]] The nested list format always uses a list of length three to represent a binary tree. The first item in...
Assume you are given “preorder” and “inorder” traversal result of a Binary Tree. Write an algorithm (pseudocode) that constructs the Binary Tree. For example, you can start with the Pre-Order and In-Order traversal of the same tree given below. Pre-Order = 80, 50, 10, 70, 100 In-Order = 10, 50, 70, 80, 100
Apply Preorder and Inorder traversal algorithms on the following binary tree and write the output. Remove node 11 from the tree and show the tree after deletion. 0007 0005 0011 0003 0006 0010 0012 0009 0024 0023
Given a binary tree, it is useful to be able to display all of its data values. For this task, define a function called basic_print() which prints out all of the data values in a binary tree. The natural way to solve this problem is to use recursion. The diagram below illustrates a recursive solution to the problem, which consists of three simple steps: Step1: Print the root node Step 3: Print the right sub-tree 10 Step 2: Print the...
Binary tree Given the following preorder and inorder traversals for an unknown binary tree, determine the exact tree that would generate these traversals and then draw that tree. Once you have generated the tree be sure to check your work. Inorder: {D, B, E, A, C, F, G, H, I} Preorder: {C, B, D, A, E, F, H, G, I}
Here you'll write the inorder traversal function in the header file "bst.h". Notice that the public inorder function calls a private recursive function _ inorder to do the actual traversal. This public-private strategy is the correct way to implement recursive functions, where the public function kicks off the recursion and the private function does the actual work. The public function is written for you, your job is to implement the private _ inorder function. he main program has been written...
I need help on question 12 please
An inorder tree traversal of a binary search tree produces a listing of the tree nodes in alphabetical or numerical order. Construct a binary search tree for "To be or not to be, that is the question, " and then do an inorder traversal. Construct a binary search tree for "In the high and far off times the Elephant, O Best Beloved, had no trunk, " and then do an inorder traversal.
Python Given the root to a binary tree, implement serialize(root), which serializes the tree into a string, and deserialize(s), which deserializes the string back into the tree. For example, given the following Node class class Node: def __init__(self, val, left=None, right=None): self.val = val self.left = left self.right = right The following test should pass: node = Node('root', Node('left', Node('left.left')), Node('right')) assert deserialize(serialize(node)).left.left.val == 'left.left'
There are generally considered to be four distinct binary tree traversals: preorder, inorder, postorder and level-order. Consider the following questions about these different kinds of traversals. Answer one of them that has not already been answered. What is the result of the various tree traversals when performed on an arithmetic expression tree? Which of the traversals are depth-first? Which are breadth-first? Which kind of traversal of a binary search tree produces the values in sorted order? Which of the traversals...