Open the context
Choose the project folder and name the files or behavior involved.
Rebuild a binary tree from preorder and inorder lists of at most 100 distinct integer labels. Test empty and skewed trees, rejecting inconsistent traversals or repeated labels without editing either input.
Choose the project folder and name the files or behavior involved.
Describe the input, expected output and boundaries that must stay intact.
Review the proposed edits and any commands before relying on their result.
Compare actual behavior with the expected result. If a check fails, investigate it before applying more changes.
def rebuild_tree(preorder, inorder):
for row in (preorder,inorder):
if type(row) not in (list,tuple) or len(row) > 100 or any(type(v) is not int for v in row):
raise ValueError("at most 100 integer nodes")
if len(set(preorder)) != len(preorder) or len(set(inorder)) != len(inorder) or set(preorder) != set(inorder):
raise ValueError("same distinct node labels")
positions, cursor = {v:i for i,v in enumerate(inorder)}, 0
def visit(lo,hi):
nonlocal cursor
if lo == hi: return None
value = preorder[cursor]; cursor += 1
at = positions[value]
if not lo <= at < hi: raise ValueError("inconsistent traversals")
left = visit(lo,at)
right = visit(at+1,hi)
return value,left,right
return visit(0,len(inorder))The example is a starting point for a real project, not a claim that generated code is already tested. Adjust paths, dependencies and expected behavior to match your application.