Construct Binary Tree from Preorder and Inorder Traversal
Construct and return the binary tree from preorder and inorder traversals Example: preorder=[3,9,20,15,7], inorder=[9,3,15,20,7] => [3,9,20,null,null,15,7]
Preorder hands me each root. Inorder shows what sits left and right of it, so I recurse on both halves.
Examples
You write
build_tree(preorder: List[int], inorder: List[int])
Example 1
- Input
- preorder = [3,9,20,15,7], inorder = [9,3,15,20,7]
- returns
- [3,9,20,null,null,15,7]
Example 2
- Input
- preorder = [-1], inorder = [-1]
- returns
- [-1]
The pattern behind it
Arrays & Hashing
I reach for it when
- You catch yourself scanning the array again for every element.
- The problem asks about duplicates, pairs, counts or groups.
Say this before you type. Say what the key is and what the value remembers, before you write the loop.
All 127 Arrays & Hashing problemsTrees
I reach for it when
- Each node has children, and the answer depends on the subtrees.
- The statement says depth, height, ancestor or path.
Say this before you type. Say what a call returns for an empty tree, and what it returns for a node.
All 22 Trees problems
Meet Coco
Coco is an AI study partner, not a person. She listens while you explain your code, asks what a line does and never hands you the fix. Sign in free to type with Coco, up to a daily limit. The editor and Run stay open without an account. Anyone can open the editor and run their code.