Worked example and algorithm walkthrough
Topic: Binary Trees · Structure and paths
Follow the computed execution on the reference input. Advance one step at a time, inspect the changing values and compare your prediction with the final output.
Example input
{
"inorder": [
4,
2,
5,
1,
3,
6
],
"order": [
1,
2,
4,
5,
3,
6
],
"post": false
}Execution steps
- Place subtree root
Computed output
[ 1, 2, 3, 4, 5, null, 6 ]
JavaScript reference implementation
const solve = ({
inorder,order,post
},s)=>{
let a=[],p=post?order.length-1:0;
function f(l,r,i){
if(l>r)return;
let v=order[p];
p+=post?-1:1;
a[i]=v;
let m=inorder.indexOf(v);
s("Place subtree root",{
Inorder:inorder,Order:order,Tree:nodes(a),Current:[i]
});
if(post){
f(m+1,r,2*i+2);
f(l,m-1,2*i+1)
}else{
f(l,m-1,2*i+1);
f(m+1,r,2*i+2)
}
}
f(0,inorder.length-1,0);
return Array.from(a,x=>x??null)
};
function exists(a,i){
return i<a.length&&a[i]!=null
}
function nodes(a){
return a.map((v,i)=>v==null?null:[i,v,exists(a,2*i+1)?2*i+1:null,exists(a,2*i+2)?2*i+2:null]).filter(Boolean)
}
function ordered(a,s,mode){
let o=[];
function f(i){
if(!exists(a,i))return;
if(mode==="pre"){
o.push(a[i]);
s("Visit node before children",{
Tree:nodes(a),Visited:o,Current:[i]
})
}
f(2*i+1);
if(mode==="in"){
o.push(a[i]);
s("Visit node between children",{
Tree:nodes(a),Visited:o,Current:[i]
})
}
f(2*i+2);
if(mode==="post"){
o.push(a[i]);
s("Visit node after children",{
Tree:nodes(a),Visited:o,Current:[i]
})
}
}
f(0);
return o
}