14
$\begingroup$

I use the following code to generate a binary tree with root 1.

TreePlot[{1 -> 2, 1 -> 3, 2 -> 4, 2 -> 5, 3 -> 6, 3 -> 7, 4 -> 8, 
  4 -> 9, 5 -> 10, 5 -> 11, 6 -> 12, 6 -> 13, 7 -> 14, 7 -> 15, 
  8 -> 16, 8 -> 17, 10 -> 18, 10 -> 19, 11 -> 20, 11 -> 21, 13 -> 22, 
  13 -> 23, 15 -> 24, 18 -> 25, 18 -> 26, 19 -> 27, 19 -> 28, 
  25 -> 29, 25 -> 30, 26 -> 31, 31 -> 32, 31 -> 33}, 
 VertexLabeling -> True]

However, it generates a non-binary-looking tree with 2 as the "root". enter image description here

Anyone has solution for this? Thank you!

$\endgroup$

1 Answer 1

21
$\begingroup$

The documentation says:

TreePlot[g] attempts to choose the root so as to make trees have as few layers as possible.

What it does not say is that edge directions are ignored when determining the root node. The result is that TreePlot rejects the expected tree rooted at 1 because it has eight layers as opposed to the seven layers obtained with 2 as the root.

While this behaviour might be less than useful, the good news is that if we explicitly specify the proper root node then the tree is rendered nicely:

TreePlot[
  { 1 -> 2, 1 -> 3, 2 -> 4, 2 -> 5, 3 -> 6, 3 -> 7, 4 -> 8
  , 4 -> 9, 5 -> 10, 5 -> 11, 6 -> 12, 6 -> 13, 7 -> 14, 7 -> 15
  , 8 -> 16, 8 -> 17, 10 -> 18, 10 -> 19, 11 -> 20, 11 -> 21
  , 13 -> 22, 13 -> 23, 15 -> 24, 18 -> 25, 18 -> 26, 19 -> 27
  , 19 -> 28, 25 -> 29, 25 -> 30, 26 -> 31, 31 -> 32, 31 -> 33
  }
, Top
, 1
, VertexLabeling -> True
]

enter image description here

Note the addition of the arguments Top and 1 which indicate that the tree should be rooted at the top of the diagram and that the root node should be 1.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.