如何使用此处给出的代码标记哈夫曼树

如何使用此处给出的代码标记哈夫曼树
\begin{frame}
\frametitle{\textbf{Huffman Coding}}
\begin{figure}
\centering \scalebox{0.6}{
\begin{tikzpicture}
 \tikzstyle{iv}=[draw,fill=red!50,circle,minimum size=20pt,inner sep=0pt,text=black]
 \tikzstyle{ev}=[draw,fill=yellow,rectangle,minimum size=20pt,inner sep=0pt,text=black]
\node[iv]{31}
  child {node[iv]{18}
         child {node[iv]{11}
                child {node[iv]{6}
                       child {node[iv]{3}
                              child {node[ev]{E(1)}}
                              child {node[ev]{C(2)}}
                             }
                       child {node[ev]{B(3)}}
                      }
                child {node[ev]{D(5)}}
                }
         child [missing]
         child {node[iv]{7}
         child {node[ev]{A(4)}}
         child {node[ev]{G(3)}}
               }
        }
  child [missing]
  child [missing]
  child {node[iv]{13}
         child {node[ev]{F(6)}}
         child {node[ev]{H(7)}}
        }
;
\end{tikzpicture}}
\vspace{-0.1cm} \caption{Huffman tree}
\end{figure}
\end{frame}

在此处输入图片描述

答案1

您可以使用 添加边缘标签edge from parent node

\documentclass[tikz,border=3.14mm]{standalone}
\usetikzlibrary{trees}
\begin{document}
\begin{tikzpicture}[iv/.style={draw,fill=red!50,circle,minimum size=20pt,inner
sep=0pt,text=black},ev/.style={draw,fill=yellow,rectangle,minimum
size=20pt,inner sep=0pt,text=black}]
\node[iv]{31}
  child {node[iv]{18}
         child {node[iv]{11}  
                child {node[iv]{6}
                       child {node[iv]{3}
                              child {node[ev]{E(1)}}
                              child {node[ev]{C(2)}}
                             }
                       child {node[ev]{B(3)}}
                      }
                child {node[ev]{D(5)}}
                }
         child [missing]
         child {node[iv]{7}
         child {node[ev]{A(4)}}
         child {node[ev]{G(3)}}
               }
        edge from parent node[above]{O}        
        }
  child [missing]
  child [missing]
  child {node[iv]{13}
         child {node[ev]{F(6)}}
         child {node[ev]{H(7)}}
        };
\end{tikzpicture}
\end{document}

在此处输入图片描述

然而,这相当麻烦。因此,我想宣传一下forest,其中已经提出了一个自动化解决方案这个答案

\documentclass{article}
\usepackage[edges]{forest}
\tikzset{iv/.style={draw,fill=red!50,circle,minimum size=20pt,inner
sep=0pt,text=black},ev/.style={draw,fill=yellow,rectangle,minimum
size=20pt,inner sep=0pt,text=black}}
\begin{document}
\begin{forest}
for tree={where n children={0}{ev}{iv},l+=8mm,
% from https://tex.stackexchange.com/a/304002/121799
if n=1{edge label={node [midway, left] {0} } }{edge label={node [midway, right] {1} } },}
[31
 [18
  [11%,el=O  
   [6
    [3
     [E(1)]
     [C(2)]
    ]
    [B(3)]
   ] 
   [D(5)]
  ] 
  [7
   [A(4)]
   [G(3)]
  ] 
 ]  
 [13
  [F(6)]
  [H(7)]
 ] 
] 
\end{forest}
\end{document}

在此处输入图片描述

相关内容