A depth-first binary tree.
Log in to post a comment.
Canvas.setpenopacity(0.85); const turtle = new Turtle(); const nodeDistance = 10; const maxDepth = 10; const angle = 90; const positions = [{x: 0, y: 30, h: 180, r: true, d: 0}]; const savePos = (x, y, h, r, d) => positions.push({x, y, h, r, d}); const getLastPos = () => positions.pop(); function walk(i) { const lastPos = getLastPos(); if (!lastPos) return false; // stop drawing when the tree is done turtle.penup(); turtle.goto(lastPos.x, lastPos.y); turtle.setheading(lastPos.h); turtle.pendown(); if (lastPos.r) { turtle.right(angle/(lastPos.d+1)); turtle.forward(nodeDistance); if (lastPos.d < maxDepth) { savePos(turtle.x(), turtle.y(), turtle.h(), true, lastPos.d+1); savePos(turtle.x(), turtle.y(), turtle.h(), false, lastPos.d+1); } } else { turtle.left(angle/(lastPos.d+1)); turtle.forward(nodeDistance); if (lastPos.d < maxDepth) { savePos(turtle.x(), turtle.y(), turtle.h(), false, lastPos.d+1); savePos(turtle.x(), turtle.y(), turtle.h(), true, lastPos.d+1); } } return i < 20000; }