我需要在树上画一条不同的路径来描绘树上发生的两种不同情况。具体来说,我能够描绘出带有森林的遍历树,如下图所示,这将描绘出从根到叶的情况。
但是我还需要用不同的颜色和从子节点指向父节点的不同箭头来计算从叶子节点到根节点的情况,而我不知道从哪里开始。
\documentclass[letterpaper,12pt]{article}
\usepackage{blindtext}
\usepackage{tikz}
\usepackage{forest}
\usepackage{xcolor}
\usepackage{float}
\usetikzlibrary{calc}
\newcounter{nodeidx}
\newcounter{example}
\setcounter{nodeidx}{1}
\usetikzlibrary{
calc,
arrows.meta,
%shapes.multipart,
%arrows
}
\newcommand{\nodes}[1]{%
\foreach \num [count=\n starting from 0] in {#1}{% no need for an external counter
\node[minimum size=6mm, draw, rectangle] (n\n) at (\n,0) {\num};
}
}
\begin{document}
\begin{figure}[H]
\centering
\begin{forest}
for tree = {
rectangle split,
rectangle split horizontal,
rectangle split parts=10,
rectangle split ignore empty parts,
draw,
%
parent anchor=south,
child anchor=north,
calign=edge midpoint,
edge = {-Stealth, semithick},
l sep=6mm,
where level=0{s sep=11mm}{s sep=3mm},
}
[2 \nodepart{two} 4 \nodepart{three} 3 \nodepart{four} 1 \nodepart{five} 6
\nodepart{six} 7 \nodepart{seven} 8 \nodepart{eight} 9 \nodepart{nine} 1 \nodepart{ten} 7, color={red}
[2\nodepart{two} 2 \nodepart{two} 4 \nodepart{three} 3 \nodepart{four} 1 \nodepart{five} 6
[2\nodepart{two} 4
[2] [4]]
[3\nodepart{two} 1 \nodepart{three} 6
[3] [1 \nodepart{two} 6
[1] [6]
]]
]
[7 \nodepart{two} 8 \nodepart{three} 9 \nodepart{four} 1
\nodepart{six} 7,fit=band, color={red}
[7 \nodepart{two} 8
[7]
[8]
]
[9\nodepart{two} 1 \nodepart{three} 7, color={red}
[9]
[1\nodepart{two} 7, color={red}
[10, color={green}]
[7]
]
]
]
]
\end{forest}
\end{figure}
\end{document}
谢谢您的帮助。
答案1
一个简单的解决方案是手动添加边缘的颜色:
\documentclass[letterpaper,12pt]{article}
\usepackage{blindtext}
\usepackage{forest}
\usetikzlibrary{arrows.meta}
\begin{document}
\begin{figure}[ht]
\centering
\begin{forest}
for tree = {
rectangle split,
rectangle split horizontal,
rectangle split parts=10,
rectangle split ignore empty parts,
draw,
%
parent anchor=south,
child anchor=north,
calign=edge midpoint,
edge = {-Stealth, semithick},
l sep=6mm,
where level=0{s sep=11mm}{s sep=3mm},
}
[2 \nodepart{two} 4 \nodepart{three} 3 \nodepart{four} 1 \nodepart{five} 6
\nodepart{six} 7 \nodepart{seven} 8 \nodepart{eight} 9 \nodepart{nine} 1 \nodepart{ten} 7, color=red,
[2\nodepart{two} 2 \nodepart{two} 4 \nodepart{three} 3 \nodepart{four} 1 \nodepart{five} 6
[2\nodepart{two} 4
[2] [4]]
[3\nodepart{two} 1 \nodepart{three} 6
[3] [1 \nodepart{two} 6
[1] [6]
]]
]
[7 \nodepart{two} 8 \nodepart{three} 9 \nodepart{four} 1
\nodepart{six} 7,fit=band, color=red,edge=red
[7 \nodepart{two} 8
[7]
[8]
]
[9\nodepart{two} 1 \nodepart{three} 7, color=red,edge=red
[9]
[1\nodepart{two} 7, color=red,edge=red
[10, color=green,edge=green]
[7]
]
]
]
]
\end{forest}
\end{figure}
\end{document}