Mathematica Stack Exchange is a question and answer site for users of Mathematica. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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!

share|improve this question
up vote 20 down vote accepted

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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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