⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 tree.tex

📁 一个德国人Kasper Peeters用C++ template写的tree的STL实现
💻 TEX
字号:
\documentclass[11pt]{kasper}% % If you do not have 'kasper.cls', see% http://www.damtp.cam.ac.uk/user/kp229/texstuff .\usepackage{makeidx}\usepackage{verbatim}\usepackage{relsize}\makeindex%\newcommand{\toindex}[1]{#1\index{#1}}\newcommand{\member}[1]{{\tt #1}\index{#1}}%\newcommand{\member}[1]{{\tt #1}}\def\mystrut{\vbox to 8.5pt{}\vtop to 3.5pt{}}\def\V{\hskip10pt\vrule\hskip10pt}\def\T{\hskip10pt\vrule\vrule height2.5pt depth -2.1pt width 10pt}\def\L{\hskip10pt\vrule height 8.5pt depth -2.1pt       \vrule height2.5pt depth -2.1pt width 10pt}\def\N{\hskip10pt\phantom{\vrule}\hskip10pt}\def\hw{\hskip-1000pt plus 1fil}% to test: insert before end of subtree\begin{document}\title{{\tt tree.hh} documentation}\author{Kasper Peeters}\address{1}{{\it MPI/AEI f\"ur Gravitationsphysik, Am M\"uhlenberg 1, 14476Potsdam, Germany}}\email{k.peeters@damtp.cam.ac.uk}\maketitle\begin{abstract}The {\tt tree.hh} library for C++ provides an STL-like container classfor n-ary trees, templated over the data stored at the nodes.  Varioustypes of iterators are provided (post-order, pre-order, andothers). Where possible the access methods are compatible with the STLor alternative algorithms are available. The library is availableunder the terms of the GNU General Public License.\\[3ex]Code and examples available at: {\tt http://www.damtp.cam.ac.uk/user/kp229/tree/}\\[3ex]{\bf This documentation is not yet complete. Refer to the {\tttree.hh} header file for a full list of member functions.}\end{abstract}\maketoc\begin{sectionunit}\title{Overview}\maketitle\begin{sectionunit}\title{The container class}\maketitleThe tree class of {\tt tree.hh} is a templated container class in thespirit of the STL. It organises data in the form of a so-called n-arytree. This is a tree in which every node is connected to an arbitrarynumber of child nodes. Nodes at the same level of the tree are called``siblings'', while nodes that are below a given node are called its``children''. At the top of the tree, there is a set of nodes whichare characterised by the fact that they do not have any parents. Thecollection of these nodes is called the ``head'' of the tree. Seefigure~\ref{f:overview} for a pictorial illustration of thisstructure (90 degrees rotated for convenience).\begin{figure}[th]\begin{center}\includegraphics[width=.5\textwidth]{treefig}\caption{Overview of the tree structure. The elements at the top ofthe tree (here displayed at the left for convenience) are in the``head'' (there can be more than one such element).  Every node islinked to its children using the ``first child'' and ``last child''links. In addition, all nodes on a given level are doubly-linked usingthe ``previous sibling'' and ``next sibling'' links. The ``depth'' ofa given node refers to the horizontal distance from the head nodes.}\label{f:overview}\end{center}\end{figure}The tree class is templated over the data objects stored at the nodes;just like you can have a {\tt vector<string>} you can now have a{\tt tree<string>}. Many STL algorithms work on this data structure,and where necessary alternatives have been provided.\medskip\end{sectionunit}\begin{sectionunit}\title{Iterators}\maketitleThe essential difference between a container with the structure of atree and the STL containers is that the latter are ``linear''. Whilethe STL containers thus only have essentially one way in which one caniterate over their elements, this is not true for trees. The {\tttree.hh} library provides (at present) four different iterationschemes. To describe them, consider the following tree:\begin{equation*}\vcenter{\offinterlineskip\halign{&#\mystrut\hfil\cr root \hw\cr \T A \cr \V   \T  B \cr \V   \L  C \cr \L D \cr \N   \T  E \cr \N   \L  F \cr}}\end{equation*}The three iteration types and the resulting order in which nodes arevisited are tabulated below:\begin{center}\begin{tabular}{llll}pre-order (default) & ``element before children'' &\member{pre\_order\_iterator}  & root A B C D E F \\post-order          & ``element after children''  &\member{post\_order\_iterator} & B C A E F D root \\breadth-first &  &\member{breadth\_first\_iterator} & root A D B C E F  \\sibling             & ``only siblings'' & \member{sibling\_iterator} & (for ex.) A D \\fixed-depth         & &\member{fixed\_depth\_iterator} & (for ex.) B C E F \end{tabular}\end{center}The pre-order ones are the default iterators, and therefore also knownunder the name of {\tt iterator}. Sibling iterators and fixed-depthiterators iterate only over the nodes at a given depth of thetree. The former restrict themselves to the child nodes of one givennode, while the latter iterates over all child nodes at the givendepth. There are copy constructors that will convert iterators of thevarious types into each other. The post- and pre-order iterators areboth also known as ``depth-first'', in contrast to the``breadth-first'' iterator.The begin and end iterators of a tree can be obtained using\member{begin()} and \member{end()} (for pre-order iterators) oralternatively \member{begin\_post()} and \member{end\_post()} (forpost-order iterators). Similarly, the begin and end sibling iteratorscan be obtained by calling \member{begin(iterator)} and\member{end(iterator)}.  The range of children of a given node canalso be obtained directly from an iterator, by using the {\ttiterator::begin()} and {\tt iterator::end()} member functions.If you want to (temporarily) make an iterator not go into the childsubtree, call the member function \member{skip\_children}. This will onlykeep effect for a single increment or decrement of theiterator. Finally, whether or not an iterator is actually pointing ata node (i.e.~is not an ``end'' iterator) can be tested using the\member{is\_valid(iterator)} member of the tree class.\end{sectionunit}\end{sectionunit}\begin{sectionunit}\title{Basic operations}\maketitle\begin{description}\item[Initialising] There are two nontrivial constructors. One which takes a single node element as argument. It constructs a tree with this nodebegin the sole node in the head (in other words, it is a combinationof a trivial constructor together with a \member{set\_head} call).The other non-trivial constructor takes an iterator, and copies thesubtree starting at that node into the newly created tree (useful forconstructing new tree objects given by subtrees of existing trees).\item[Tree traversal] Besides the \member{operator++} and\member{operator--} members for step-wise traversal through the tree,it is also possible to use the \member{operator+=} and \member{operator-=}member functions to make more than one step at the same time (thoughthese are linear time, not amortized constant). The result of steppingbeyond the end of the tree or stepping beyond the end of a siblingrange (for sibling iterators) is undefined.The parent of a given node can be reached by calling the \member{parent}member of the tree object, giving it an iterator pointing to the node.If you know the number of children of a given node, you can get directaccess to the $n$th child by using the \member{child} memberfunction. Note that the value of the index is not checked and shouldtherefore always be valid.\item[Appending child nodes] Nodes can be added as children of a givennode using the \member{append\_child} member function.\item[Inserting nodes] Nodes can be inserted at the same depth as agiven other node using the \member{insert} and \member{insert\_after}members functions. This is also how you insert the first node into a tree.\end{description}\end{sectionunit}\begin{sectionunit}\title{Other algorithms}\maketitle\begin{sectionunit}\title{Non-mutating algorithms}\maketitle\begin{description}\item[Counting nodes] The total number of nodes of a tree can beobtained using the \member{size} member function, while the number ofchildren of a given node can be obtained with a call to\member{number\_of\_children(iterator)}. Similarly, the number ofnodes at a given depth (the number of siblings of a given node) can beobtained using the \member{number\_of\_siblings} member function.\item[Determining depth] The \member{depth()} member function returns thedistance of a node to the root.\item[Accessing siblings by their index] See the next item.\item[Determining index in a sibling range] In order to determine theindex of a node in the range of siblings to which it belongs, use the\member{index(sibling\_iterator)} member function. The first sibling nodehas index 0. The reverse of this function (obtaining a sibling nodegiven its index in the range of siblings) is called\member{child(const iterator\_base\&, unsigned int)}.\item[Comparing trees] While the STL \member{equal} algorithm can be used to compare the values of the nodes in two different trees, it does not know about the structure of the tree. If you want the comparison totake this into account, use the \member{equal(iterator, iterator,iterator, BinaryPredicate)} call of the tree class. As an addition tothe STL algorithm, the length of the first range does not have to beequal to the length of the range pointed to by the second iterator.There is also an \member{equal\_subtree} algorithm which takes onlytwo iterators, pointing to the (single-node) heads of twosubtrees.\end{description}\end{sectionunit}\begin{sectionunit}\title{Mutating algorithms}\maketitle\begin{description}\item[Erasing nodes and subtrees] In order to remove a node includingits children from the tree, use the \member{erase(iterator)} call. If youjust want to erase the children, but not the node itself, use the \member{erase\_children(iterator)} call.\item[Replacing individual nodes or subtrees] \item[Flattening subtrees] The procedure of moving all children of agiven node to be siblings of that node is called ``flattening''; itacts as\begin{equation*}\vcenter{\offinterlineskip\halign{&#\mystrut\hfil\cr apple \hw\cr \T banana\cr \V   \T  pear \cr \V   \T  strawberry \cr \V   \L  cherry \cr \L grape\cr}}\quad\rightarrow\quad\vcenter{\offinterlineskip\halign{&#\mystrut\hfil\cr apple \hw\cr \T banana\cr \T  pear \cr \T  strawberry \cr \T  cherry \cr \L grape\cr}}\end{equation*}% \begin{screen}% apple                       apple% 	  banana                      banana% 		  pear            ->       pear% 		  strawberry               strawberry% 		  cherry                   cherry% 	  grape                       grape% \end{screen}when the tree is flattened at the ``banana'' node.\item[Moving or exchanging subtrees] Simple exchange of one sibling node with thenext one is done through the member function \member{swap(sibling\_iterator)}. Theiterator remains valid and remains pointing to the moved subtree.More complicated move operations are the \member{move\_ontop},\member{move\_before} and \member{move\_after} ones. These all taketwo iterators, a source and a target. The member\member{move\_ontop(target, source)} removes the `target' node andall its children, and replaces it with the `source' node and itschildren.  The `source' subtree is removed from its original location.The other two move members do a similar thing, differing only in thenode which is to be replaced.\item[Extracting subtrees] You can create a new tree objectfilled with the data of a subtree of the original tree. This isanalogous to the extraction of a substring of a string. The relevantmember function is \member{subtree(sibling\_iterator,sibling\_iterator)} which takes a range of siblings as argument. There is also a slight variation of this member, which does not returna tree object but instead populates one that is passed as an argument(useful if you want to call this on a tree object subclassed from{\tt tree<T>}.\item[Sorting] The standard STL sort algorithm is not very useful fortrees, because it only exchanges values, not nodes. Applying it to atree would mean that the structure of the tree remains unmodified,only node values get moved around (not their subtrees).Therefore, the {\tt tree} class has its own sort member. It comes intwo forms, just like the STL sort, namely\begin{screen}void     sort(sibling_iterator from, sibling_iterator to, bool deep=false);template<class StrictWeakOrdering>void     sort(sibling_iterator from, sibling_iterator to,              StrictWeakOrdering comp, bool deep=false);\end{screen}The result of a call to either of these is that the nodes in the rangedescribed by the two iterators get sorted. If the boolean {\tt deep}is true, the subtrees of all these nodes will get sorted as well (andso one can sort the entire tree in one call).  As in the STL, you canuse the second form of this function to pass your own comparisonclass.If the nodes to which the two iterators point are not in the samesibling range (i.e.~not at the same depth in the tree), the result is undefined.\item[Merging] One way in which one might think of indicating theposition where new nodes are to be inserted, is to give the path thatleads to the insertion point.  For instance, given the tree\begin{equation*}\vcenter{\offinterlineskip\halign{&#\mystrut\hfil\cr apple \hw\cr \T banana\cr \V   \T  pear \cr \V   \T  strawberry \cr \V   \L  cherry \cr \L grape\cr}}\end{equation*}one could imagine using the sub-tree\begin{equation*}\vcenter{\offinterlineskip\halign{&#\mystrut\hfil\cr apple \hw\cr \L banana\cr \N   \T  coconut \cr \N   \L  raspberry \cr}}\end{equation*}to indicate that the nodes ``coconut'' and ``raspberry'' are to beinserted as new children of the ``banana'' node. In {\tt tree.hh} thisprocess is called \emph{tree merging}. It can do the simple additionof children as above, but actually handles the generic case too: asan example consider the merge\begin{equation*}\text{\tt merge}\left[\vcenter{\offinterlineskip\halign{&#\mystrut\hfil\cr apple \hw\cr \T banana\cr \V   \T  pear \cr \V   \T  strawberry \cr \V   \L  cherry \cr \T grape\cr blueberry \cr}}\quad, \quad\vcenter{\offinterlineskip\halign{&#\mystrut\hfil\cr apple \hw\cr \T banana\cr \V   \T coconut \cr \V   \L raspberry \cr \T tangerine \cr \V   \L plum\cr blueberry \cr \N   \L orange \cr}}\right]\quad\rightarrow\quad\vcenter{\offinterlineskip\halign{&#\mystrut\hfil\cr apple \hw\cr \T banana\cr \V   \T pear\cr \V   \T strawberry\cr \V   \T cherry\cr \V   \T coconut \cr \V   \L raspberry \cr \T grape\cr \T tangerine \cr \V   \L plum\cr blueberry \cr \N  \L orange \cr}}\end{equation*}As is clear from the above, the arguments to \member{merge} are twosibling ranges.\end{description}\end{sectionunit}\end{sectionunit}\printindex\end{document}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -