BBranchSpire
Workflows

Coding workflows · Traversal-based tree reconstruction

03
Built around your work

A concrete starting point

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.

01

Open the context

Choose the project folder and name the files or behavior involved.

02

Define the change

Describe the input, expected output and boundaries that must stay intact.

03

Inspect the work

Review the proposed edits and any commands before relying on their result.

04

Check the outcome

Compare actual behavior with the expected result. If a check fails, investigate it before applying more changes.

Traversal-based tree reconstruction

A concrete starting point
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.

AI coding workspace

Your next change starts here.

Get the Windows app ↗