Worked example and algorithm walkthrough
Topic: Binary Trees · Traversals
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
{
"a": [
1,
2,
3,
4,
5,
null,
6
],
"pre": false
}Execution steps
- Create predecessor thread
- Visit node without left child
- Remove predecessor thread
Computed output
[ 4, 2, 5, 1, 3, 6 ]
JavaScript reference implementation
const solve = ({
a,pre
},s)=>{
let l=a.map((_,i)=>exists(a,2*i+1)?2*i+1:-1),r=a.map((_,i)=>exists(a,2*i+2)?2*i+2:-1),i=0,o=[];
function emit(msg){
s(msg,{
Links:a.map((v,j)=>[j,v,l[j],r[j]]).filter(x=>x[1]!=null),Visited:o,Current:[i]
})
}
while(i!==-1){
if(l[i]===-1){
o.push(a[i]);
emit("Visit node without left child");
i=r[i]
}else{
let p=l[i];
while(r[p]!==-1&&r[p]!==i)p=r[p];
if(r[p]===-1){
if(pre)o.push(a[i]);
r[p]=i;
emit("Create predecessor thread");
i=l[i]
}else{
r[p]=-1;
if(!pre)o.push(a[i]);
emit("Remove predecessor thread");
i=r[i]
}
}
}
return o
};
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
}