How to make binary search trees in an easy and straight forward way?
This is a solution using tikz
, as an example consider the following tree
To create this code I used
\documentclass[border = 5pt, tikz]{standalone}
\begin{document}
\begin{tikzpicture}[
every node/.style = {minimum width = 2em, draw, circle},
]
\node {51}
child {node {12}}
child {node {87}};
\end{tikzpicture}
\end{document}
In this representation, it is very clear that both 12
and 87
are children of 57
. If you want to grow the tree, just keep adding children
\documentclass[border = 5pt, tikz]{standalone}
\begin{document}
\begin{tikzpicture}[
every node/.style = {minimum width = 2em, draw, circle},
level/.style = {sibling distance = 30mm/#1}
]
\node {51}
child {node {12}
child {node {1}}
child {node {43}
child {node {36}}
child {edge from parent[draw = none]}
}
}
child {node {87}
child {node {52}
child {edge from parent[draw = none]}
child {node {83}}
}
child {edge from parent[draw = none]}
};
\end{tikzpicture}
\end{document}
i would simplify tree layout as follows:
and in drawing use package forest
:
\documentclass[margin=3mm]{standalone}
\usepackage[edges]{forest}
\begin{document}
\begin{forest}
for tree={
grow=south,
circle, draw, minimum size=3ex, inner sep=1pt,
s sep=7mm
}
[51
[12
[1]
[43
[36]
]
]
[87
[52
[83]
]
]
]
\end{forest}
\end{document}
addedndum: considering caverac comment:
\documentclass[margin=3mm]{standalone}
\usepackage[edges]{forest}
\begin{document}
\begin{forest}
for tree={
grow=south,
circle, draw, minimum size=3ex, inner sep=1pt,
s sep=3mm
}
[51
[12
[1]
[43
[36]
[,no edge, draw=none]
]
]
[87
[52
[,no edge, draw=none]
[83]
]
[,no edge, draw=none]
]
]
\end{forest}
\end{document}
\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{calc}
\begin{document}
\begin{tikzpicture}[%level distance=5mm,
level 1/.style={level distance=10mm,sibling distance=24mm},
level 2/.style={level distance=10mm,sibling distance=16mm},
level 3/.style={level distance=10mm,sibling distance=16mm},
font=\scriptsize,inner sep=2pt,every node/.style={draw,circle,minimum size=3ex}]
\node {51} % root
child {node {12} % first level
child {node{1}} % 2sd level
child {node{43}
child {node{36}} % 3rd level
child[missing]
}
edge from parent }
child {node {87} % first level
child {node {52} % 2sd level
child[missing] % 3rd level
child {node{83}}
}
child[missing]
} ;
\end{tikzpicture}
\end{document}