TikZ-Trees – Drawing a Tree in LaTeX

tikz-trees

I'm trying to draw a tree using Tikz. My code is as follows:

\begin{figure}
    \centering
    \begin{tikzpicture}[node distance=1.5cm]
    \tikzstyle{process} = [rectangle, minimum width=0.7cm, minimum height=0.7cm,text centered, draw=black, fill=white!100]
    
    \tikzstyle{arrow} = [thick,->,>=stealth]
    
    \node (proA) [process] {{A}};
    \node (proB) [process, right of = proA] {{B}};
    
    \node (pro1) [process, below of = proA] {{1}};
    
    \node (pro2) [process, below of = pro1] {{$S_2$}};
    \node (pro3) [process, right of = pro2] {{$S_3$}};
    
    \node (pro6) [process, below of = pro2] {{6}};
    \node (pro7) [process, right of = pro6] {{7}};
    \node (pro8) [process, right of = pro7] {{8}};
    \node (pro9) [process, right of = pro8] {{9}};
    
    \draw [arrow] (pro1) -- (pro2);
    \draw [arrow] (pro1) -- (pro3);
    
    \draw [arrow] (pro2) -- (pro6);
    \draw [arrow] (pro2) -- (pro7);
    \draw [arrow] (pro3) -- (pro8);
    \draw [arrow] (pro3) -- (pro9);
    
    \draw [arrow] (proA) -- (pro1);
    \draw [arrow] (proB) -- (pro1);
    \end{tikzpicture}
    \label{fig:CTU_partitioning}
\end{figure}

However, it produces output similar to the right side of the image, when I require output similar to the left side.

enter image description here

How can I fix this out? There could be more levels and nodes in the tree. please suggest a smart way to draw this type of figure in latex.

Best Answer

By use of forest package (for tree below node 1) and TikZ picture for node above (for start, however there is more sophisticated way to draw complete images with forest):

enter image description here

\documentclass[border=3.141592]{standalone}
\usepackage{forest}
\usetikzlibrary{positioning}

\begin{document}
\begin{forest}
  for tree={
%   nodes
    draw, minimum size=2em, inner sep=1pt,
%   tree
    parent anchor=south,
    child anchor=north,
    l sep=7mm,
    s sep=7mm
            }
[1, name=s
    [S\textsubscript{2}
        [6]
        [7]
    ]
    [S\textsubscript{3}
        [8]
        [9]    
    ]
]
\node (a)   [draw, minimum size=2em,
             above left=7mm and 7mm of s] {A};
\node (b)   [draw, minimum size=2em,
             above right=7mm and 7mm of s] {B};
\draw (a.south) -- (s.north) -- (b.south);
\end{forest}
\end{document}