The
Constructs a two-fork tree based on the pre-order traversal and the middle sequence traversal tree. The
gives the middle-order traversal: [2,1,3] and the pre-sequence traversal: [the]. Returns the following tree:
2
/\
1 3
"" "Definition of Treenode:class treenode:def __init__ (Self, val): Self.val = Val Self.left, Self.ri
Ght = none, none "" "Class Solution:" "" @param preorder:a list of integers that preorder traversal of A tree @param inorder:a List of integers that inorder traversal of a tree @return: Root of a Tree "" "Def Buil Dtree (self, Preorder, inorder): # Write your code here if not preorder or not Inorder:return None if Len (preorder)! = Len (inorder): return None length = Len (inorder) #print "Inor Der Length= ", Length Rootkey = 0 for I in range (0,length): #print" i = ", I if Inord
Er[i] = = Preorder[0]: Rootkey = i #print "inorder[i]=", Inorder[i], "Rootkey =", rootkey,i break if Rootkey = = Length-1 and Inorder[rootkey]! = preorder[0]: return None #p Rint "root =", inorder[rOotkey] root = TreeNode (Inorder[rootkey]) #print preorder[1:rootkey],inorder[0:rootkey-1], ' nnn ', preorder[r Ootkey+1:],inorder[rootkey+1:] Root.left = Self.buildtree (Preorder[1:rootkey+1],inorder[0:rootkey]) ROOT.R ight = Self.buildtree (preorder[rootkey+1:],inorder[rootkey+1:]) return root
This has made two errors before:
1. List is empty and List = None is two different concepts, list is empty [], and List=none, is this object is none, first in the understanding of none is not very clear, but is sure not [], The first judgment statement is written as if preorder = = None or Inorder = = none, resulting in a stack overflow, instead of if not preorder or not inorder. students with specific understanding are welcome to point out the reasons under the comments . as Houmou said, when the sequence is [] The program does not intercept it but continues to pass, so Buildtree ([],[]) is called indefinitely.
2. The slice operation of list is not familiar, List = [1,2,3,4], subscript starting from 0, List[1:2] is the first element, i.e. list[1] = 2. Similarly, List[1:3] refers to the 1th, 2 elements subscript starting from 0).