user466534
user466534

Reputation:

recursive tree construction

i am going to draw recursively tree in javascript,here is what i have done still now

<!DOCTYPE HTML>
<html>
<head>
<title >Canvas  Tree </title>
</head>
<body>
<canvas id="testCanvas"  width="800" height="800" >
canvas not supported
</canvas>
<script>
var canvas=document.getElementById('testCanvas');
var ctx=canvas.getContext('2d');
var alpha=-30*Math.PI/180;
var beta=35*Math.PI/180;
function tree(){
ctx.beginPath();
ctx.moveTo(0,0);
ctx.lineTo(0,-100);
ctx.stroke();
}
ctx.translate(400,650);
tree();
ctx.translate(0,-100);
ctx.rotate(alpha);
//ctx.rotate(beta);
tree();
ctx.rotate(beta-alpha);
tree();

</script>
</body>
</html>

i think ,i need some another function which would be called recursively,in this function there would be base case,here this procedure should finish,some drawing procedure and then call itself several times,but i can't guess what should be base case,also how to implement it,please help me to implement this new function

Upvotes: 0

Views: 2170

Answers (1)

A_A
A_A

Reputation: 2368

In general, there are two ways which you can go about this:

  1. Simply "draw" a tree (i.e. draw the lines that make up your tree as you have began doing here)
  2. Render a tree data structure (using some external JS library).

The benefit of the second approach is that you can control your output much more accurately and that you don't have to write the complex code that draws the tree. Just simple code that generates the data structure.

For example, if you are specifically dealing with Binary Trees then you can create a binary tree at random in this way (Pseudocode):

function createRandomBinaryTree(aLevel):
if aLevel<4:
   thisNode = new(Node("someRandomLabel"))
   leftNode = Null
   rightNode = Null
   if random()>0.5:
      leftNode = createRandomBinaryTree(aLevel+1)
   else:
      rightNode = createRandomBinaryTree(aLevel+1)
   if leftNode!=Null:
      thisNode.leftNode = leftNode
   if rightNode!=Null:
      thisNode.rightNode = rightNode
   return thisNode
else return Null

In this case, you have a very simple data structure which is represented by a Node that has two pointers towards two other nodes (called left and right here).

(For example Node = {"label":"Root","left":{"label":"RootLeft","left":{},"right":{}},"right":{"label":"Root","RootRight":{},"right":{}}} )

You can then use something like sigmaJS (or Raphael or D3 or whatever else) to handle the actual rendering in a canvas for you.

Different Javascript libraries for producing such renderings will have their own internal formats for representing the "Node" mentioned above, so the pseudocode would have to be adapted slightly (and in any case it's not the only way to generate a binary tree at random).

I hope this helps.

Upvotes: 1

Related Questions