1+ ##==================================
2+ ## Leetcode
3+ ## Student: Vandit Jyotindra Gajjar
4+ ## Year: 2020
5+ ## Problem: 105
6+ ## Problem Name: Construct Binary Tree from Preorder and Inorder Traversal
7+ ##===================================
8+ #
9+ #Given preorder and inorder traversal of a tree, construct the binary tree.
10+ #
11+ #Note:
12+ #You may assume that duplicates do not exist in the tree.
13+ #
14+ #For example, given
15+ #
16+ #preorder = [3,9,20,15,7]
17+ #inorder = [9,3,15,20,7]
18+ #Return the following binary tree:
19+ #
20+ # 3
21+ # / \
22+ # 9 20
23+ # / \
24+ # 15 7
25+ class Solution :
26+ def buildTree (self , preorder , inorder ):
27+ l_preorder = len (preorder ) #Initialize l_preorder by finding length of preorder
28+ l_inorder = len (inorder ) #Initialize l_inorder by finding length of inorder
29+ if l_preorder != l_inorder : #Condition-check: If l_preorder and l_inorder are not the same
30+ return None #We return none as the tree is different
31+ if preorder is None : #Condition-check: If preorder is empty
32+ return None #We return none as preorder is different
33+ if inorder is None : #Condition-check: If inorder is empty
34+ return None #We return none as inorder is different
35+ if l_preorder == 0 : #If length of preorder is zero
36+ return None #We return none as preorder is different
37+ root = TreeNode (preorder [0 ]) #Initialize root by taking first value from preorder
38+ root_index = inorder .index (root .val ) #Initialize root_index by taking index from inorder's root
39+ root .left = self .buildTree (preorder [1 :root_index + 1 ], inorder [:root_index ]) #Initialize root.left by using recursion
40+ root .right = self .buildTree (preorder [root_index + 1 :], inorder [root_index + 1 :]) #Initialize root.right by using recursion
41+ return root #We return root after no value is present in preorder or inorder
42+
0 commit comments