You are on page 1of 55

Rooted Tree

A rooted tree is a tree with a countable number of nodes, in which a particular node is distinguished from the others and called the root:

In some contexts, in which only a rooted tree would make sense, the term tree is often used.

Infinite Tree
A rooted tree is infinite if it contains a countably infinite number of nodes.

Finite Tree
Similarly, a rooted tree is finite if it contains a finite number of nodes.

Parent
Consider a rooted tree T whose root is r T

Let t be a node of T From Paths in Trees are Unique, there is only one path from t to r T Let :T{r T

}T be the mapping defined as: (t)= the node adjacent to t on the path to r T

Then (t) is known as the parent (or parent node) of t , and as the parent function or parent mapping.

Root Node
The root node, or just root, is the one node in a rooted tree which, by definition, has no parent.

Ancestor
An ancestor (or ancestor node) of a node t of a rooted tree T whose root is r T is a node in the path from t to r T . Thus, the root of a rooted tree T is the ancestor of every node of T (including itself).

Proper Ancestor
A proper ancestor of a node t is an ancestor of t which is not t itself.

Children
The children (or child nodes) of a node t in a rooted tree T are the elements of the set:

{sT:(s)=t}
That is, the children of t are all the nodes of T of which t is the parent.

The child of a child node of a node t is a grandchild node of t .

Descendant
A descendant (or descendant node) s of a node t of a rooted tree T whose root is r T is a node such that t is in the path from s to r T . That is, the descendants of t are all the nodes of T of which t is an ancestor.

Proper Descendant
A proper descendant of a node t is a descendant of t which is not t itself.

Sibling
Two children of the same node of a rooted tree are called siblings. That is, siblings are nodes which both have the same parent.

Leaf Node
A leaf node (or a terminal node, or just leaf) of a rooted tree T is a node of T which has no children.

Branch
A subset of a rooted tree T is a branch iff:

The root node r T belongs to ; The parent of each node in {r T } is in ; Each node in either: o Is a leaf node of T ; o Has exactly one child in .

Hence a node in T with more than one child will be on more than one branch. A leaf node will be on exactly one branch.

The length of a branch is defined as the number of ancestors of the leaf at the end of that branch.

Informally, then, a branch of a rooted tree is the path from the root to a leaf. Note, however, that is infinite iff it has no leaf node at the end.

Sources

Tree (graph theory)


From Wikipedia, the free encyclopedia

Jump to: navigation, search This article includes a list of references, related reading or external links, but its sources remain unclear because it lacks inline citations. Please improve this article by introducing more precise citations. (March 2012)

Trees

A labeled tree with 6 vertices and 5 edges

Vertices

Edges

v-1

Chromatic number

2 if v > 1

v t e

In mathematics, more specifically graph theory, a tree is an undirected graph in which any two vertices are connected by exactly one simple path. In other words, any connected graph without cycles is a tree. A forest is a disjoint union of trees. The various kinds of data structures referred to as trees in computer science are equivalent to trees in graph theory, although such data structures are commonly rooted trees, and may have additional ordering of branches.

Contents
[hide]

1 Definitions 2 Example 3 Facts 4 Enumeration o 4.1 Labeled trees o 4.2 Unlabeled trees 5 Types of trees 6 See also 7 References

[edit] Definitions
A tree is an undirected simple graph G that satisfies any of the following equivalent conditions:

G is connected and has no cycles. G has no cycles, and a simple cycle is formed if any edge is added to G. G is connected, but is not connected if any single edge is removed from G.

G is connected and the 3-vertex complete graph is not a minor of G. Any two vertices in G can be connected by a unique simple path.

If G has finitely many vertices, say n of them, then the above statements are also equivalent to any of the following conditions:

G is connected and has n 1 edges. G has no simple cycles and has n 1 edges.

An irreducible (or series-reduced) tree is a tree in which there is no vertex of degree 2. A forest is an undirected graph, all of whose connected components are trees; in other words, the graph consists of a disjoint union of trees. Equivalently, a forest is an undirected cycle-free graph. As special cases, an empty graph, a single tree, and the discrete graph on a set of vertices (that is, the graph with these vertices that has no edges), all are examples of forests. The term hedge sometimes refers to an ordered sequence of trees. A polytree or oriented tree is a directed graph with at most one undirected path between any two vertices. In other words, a polytree is a directed acyclic graph for which there are no undirected cycles either. A directed tree is a directed graph which would be a tree if the directions on the edges were ignored. Some authors restrict the phrase to the case where the edges are all directed towards a particular vertex, or all directed away from a particular vertex (see arborescence). A tree is called a rooted tree if one vertex has been designated the root, in which case the edges have a natural orientation, towards or away from the root. The tree-order is the partial ordering on the vertices of a tree with u v if and only if the unique path from the root to v passes through u. A rooted tree which is a subgraph of some graph G is a normal tree if the ends of every edge in G are comparable in this tree-order whenever those ends are vertices of the tree (Diestel 2005, p. 15). Rooted trees, often with additional structure such as ordering of the neighbors at each vertex, are a key data structure in computer science; see tree data structure. In a context where trees are supposed to have a root, a tree without any designated root is called a free tree. In a rooted tree, the parent of a vertex is the vertex connected to it on the path to the root; every vertex except the root has a unique parent. A child of a vertex v is a vertex of which v is the parent. A leaf is a vertex without children. A labeled tree is a tree in which each vertex is given a unique label. The vertices of a labeled tree on n vertices are typically given the labels 1, 2, , n. A recursive tree is a labeled rooted tree where the vertex labels respect the tree order (i.e., if u < v for two vertices u and v, then the label of u is smaller than the label of v). An ordered tree or plane tree is a rooted tree for which an ordering is specified for the children of each vertex.

An n-ary tree is a rooted tree for which each vertex has at most n children. 2-ary trees are sometimes called binary trees, while 3-ary trees are sometimes called ternary trees. A terminal vertex of a tree is a vertex of degree 1. In a rooted tree, the leaves are all terminal vertices; additionally, the root, if not a leaf itself, is a terminal vertex if it has precisely one child.

[edit] Example
The example tree shown to the right has 6 vertices and 6 1 = 5 edges. The unique simple path connecting the vertices 2 and 6 is 2-4-5-6.

[edit] Facts

Every tree is a bipartite graph and a median graph. Every tree with only countably many vertices is a planar graph. Every connected graph G admits a spanning tree, which is a tree that contains every vertex of G and whose edges are edges of G. Every connected graph with only countably many vertices admits a normal spanning tree (Diestel 2005, Prop. 8.2.4). There exist connected graphs with uncountably many vertices which do not admit a normal spanning tree (Diestel 2005, Prop. 8.5.2). Every finite tree with n vertices, with n > 1, has at least two terminal vertices (leaves). This minimal number of terminal vertices is characteristic of path graphs; the maximal number, n 1, is attained by star graphs. For any three vertices in a tree, the three paths between them have exactly one vertex in common.

[edit] Enumeration
[edit] Labeled trees
Cayley's formula states that there are nn2 trees on n labeled vertices. It can be proved by first showing that the number of trees with vertices 1,2,...,n, of degrees d1,d2,...,dn respectively, is the multinomial coefficient

An alternative proof uses Prfer sequences.

Cayley's formula is the special case of complete graphs in a more general problem of counting spanning trees in an undirected graph, which is addressed by the matrix tree theorem. The similar problem of counting all the subtrees regardless of size has been shown to be #P-complete in the general case (Jerrum (1994)).

[edit] Unlabeled trees


Counting the number of unlabeled free trees is a harder problem. No closed formula for the number t(n) of trees with n vertices up to graph isomorphism is known. The first few values of t(n) are: 1, 1, 1, 1, 2, 3, 6, 11, 23, 47, 106, 235, 551, 1301, 3159, ... (sequence A000055 in OEIS). Otter (1948) proved the asymptotic estimate:

with C = 0.534949606 and = 2.99557658565. (Here, .) This is a consequence of his asymptotic estimate for the number trees with n vertices:

means that of unlabeled rooted

with D = 0.43992401257 and the same as above (cf. Knuth (1997), Chap. 2.3.4.4 and Flajolet & Sedgewick (2009), Chap. VII.5).

[edit] Types of trees


A star graph is a tree which either has order n 2, or consists of a single internal node (and n 1 leaves). In other words, a star graph of order n is a tree of order n with as many leaves as possible. Its diameter is at most 2. A tree with two terminal vertices (the fewest possible) is a path graph. If all nodes in a tree are within distance one of a central path subgraph, then the tree is a caterpillar tree. If all nodes are within distance two of a central path subgraph, then the tree is a lobster.

[edit] See also


Decision tree Pseudoforest Tree structure Tree data structure Unrooted binary tree

[edit] References
Wikimedia Commons has media related to: decision diagrams

Diestel, Reinhard (2005), Graph Theory (3rd ed.), Berlin, New York: Springer-Verlag, ISBN 978-3-540-26183-4, http://diestel-graph-theory.com/index.html. Flajolet, Philippe; Sedgewick, Robert (2009), Analytic Combinatorics, Cambridge University Press, ISBN 978-0-521-89806-5 Donald E. Knuth. The Art of Computer Programming Volume 1: Fundamental Algorithms. Addison-Wesley Professional; 3rd edition (November 14, 1997). Jerrum, Mark (1994), "Counting trees in a graph is #P-complete", Information Processing Letters 51 (3): 111116, doi:10.1016/0020-0190(94)00085-9, ISSN 0020-0190. Otter, Richard (1948), "The Number of Trees", Annals of Mathematics, Second Series 49 (3): 583599, doi:10.2307/1969046, JSTOR 1969046.

Retrieved from "http://en.wikipedia.org/w/index.php?title=Tree_(graph_theory)&oldid=482495260" View page ratings

Rate this page


What's this? Trustworthy Objective Complete Well-written

I am highly knowledgeable about this topic (optional) Submit ratings Saved successfully Your ratings have not been submitted yet Categories: Trees (graph theory) Hidden categories: Articles lacking in-text citations from March 2012 All articles lacking in-text citations

31 Rooted Trees

31.1 Definitions for Rooted Trees

DEFINITION: A tree is a set of nodes, perhaps empty. If not empty, there is a distinguished node r, called root and zero or more subtrees T1,T2,.....Tk each of whose roots are connected by a directed edge to r. The root of each subtree is called a child of r, and r is called the parent of each child. DEFINITION: Nodes with no children are called leaf nodes. All other nodes are called interior nodes. DEFINITION: The degree of a node is the number of its children. The degree of a tree is the maximum degree of any of its nodes. DEFINITION: Nodes with the same parent are called siblings. There is such a thing as a NULL tree -- a tree with no nodes. Not every author allows this. Trees defined this way are "rooted'' trees. They have a distinguished root. Not all trees are considered to be rooted. Nodes are sometimes called vertices or points; edges are sometimes called lines. Note that the edges are directed edges. This means there is a direction associated with them. This definition has the edges directed to the root. Nobody draws the edges as directed edges, it's just understood.

The figure shows a rooted tree with edges undirected from child to parent. The nodes are labelled for convenience. The tree has degree 3 since the node with maximum degree (the root, node A) has degree 3. The more traditional way to draw the tree is with undirected edges; this is also shown in the figure.

Generic trees are usually shown in a schematic form with the subtrees indicated by triangles. The firgure below shows such a representation. The details of the subtrees are hidden in the "triangles'"

DEFINITION: A path from node n1 to node nk is a sequence of nodes n1, n2,....., nk such that ni is the parent of n i+1 for 1 <= i < k. The length of this path is the number of edges on the path (namely k - 1) There is a path of length zero from every node to itself. In a tree there is one and only one path from the root to each node. DEFINITION: The depth of a node is the length of the path from the root to the node The root is at depth 0. DEFINITION: The depth of a tree is the depth of its deepest leaf. DEFINITION: The height of any node is the longest path from the node to any leaf. The height of any leaf is 0. DEFINITION: The height of a tree is the height of its root. The height and depth of a tree are equal. DEFINITION: If there is a path from node ni to node nj, then node ni is an ancestor of node nj and node nj is a descendent of node ni. Every node is both an ancestor and a descendent of itself. An ancestor (descendent) of a node which is not the node itself is called a proper ancestor (descendent) of the node.

31.2 Theorems about Trees


Theorem There are n - 1 edges in any tree with n nodes

Proof: Each edge connects a node to its parent. Every node except the root has a parent.

31.3 FirstChild, NextSibling Representation of General Rooted Trees


One could imagine representing a general node as a struct: struct general_node { Element_Type element; general_node * child1; general_node * child2; general_node * child3; general_node * child4; . . . }; An obvious problem with this representation is that the number of children would have to be large enough to cover all the expected cases. This would usually mean wasting a lot of pointers. A better representation is the ``firstchild, nextsibling'' representation. struct general_node { Element_Type element; general_node *first_child; general_node *next_sibling; };

The figure below shows the "firstchild, nextsibling" representation of the rooted tree shown above.. The downwardpointing edges are the "first-child" edges. The horizontal edges are the "next-sibling" edges.

32 Binary Trees

DEFINITION: A binary tree is a rooted tree in which no node can have more than two children, and the children are distinguished as left and right. Not every rooted tree with degree two is a binary tree. The children must be in order -- there is a "left'' child and a "right'' child. DEFINITION: A full binary tree is one in which every leaf node is at the same level, and every interior node has exactly two children. DEFINITION: A complete binary tree is a full binary tree except perhaps for the final level which is filled from left to right.

Here's the definition of a Tree Node for binary trees. It keeps pointers to its left and right children. // forward declaration template <class Etype> class Binary_Search_Tree;

template <class Etype> class Tree_Node { protected: Etype Element; Tree_Node *Left; Tree_Node *Right; Tree_Node( Etype E = 0, Tree_Node *L = NULL, Tree_Node *R = NULL ) : Element( E ), Left( L ), Right( R ) { } friend class Binary_Search_Tree<Etype>; }; Binary Search Tree is made a friend of Tree Node. The constructor takes an element and two pointers as arguments (with default values for all). The constructor can be called in any of the following ways: 1. Tree_Node(); in this case Element will be 0, and both Left and Right children will be NULL. 2. Tree_Node(elementvalue); in this case, Element will have the value elementvalue, Left and Right will be NULL. 3. Tree_Node(elementvalue, nodeptr1); in this case, Element will have the value elementvalue, Left will have the value nodeptr1 and Right will be NULL. < BR> 4. Tree_Node(elementvalue, nodeptr1, nodeptr2); in this case, Element will have the value elementvalue, Left will have the value nodeptr1 and Right will have the value nodeptr2.

32.1 Theorems About Binary Trees

Theorem 32.1 If a binary tree (BT) of height h has t leaves, then h >= lg t Proof: If h >= lg t, then equivalently t <= 2 h . We prove the latter by induction on h. Base: h = 0 (single node). Therefore, t = 1 = 20

IH: Assume true for every BT with height less than h Let T be a BT of height h > 0 and with t leaf nodes. We consider two possible cases: Case 1: Root of T has only one child. Without loss of generality, let it be the left child. Then the left subtree has height h - 1 and it has all the leaf nodes of T. By IH, t <= 2 h - 1 < 2h Case 2: Root has two children. Let t1 and t2 be the number of leaf nodes and h 1 and h 2 the heights of the two subtrees, respectively. Since the leaf nodes of T are partitioned between the two subtrees, t = t1 + t2 . By IH, t1 <= 2h1 and t 2 <= 2 h 2 . Also, h1 <= h - 1 and h 2 <= h - 1 Therefore, t <= 2h1 + 2h2 t <= 2h - 1 + 2h - 1 t <= 2h

Theorem 32.2 A full binary tree (FBT) of height h has 2h leaf nodes. Proof: By induction on h Base: A FBT of height 0 has 1 node (the root). IH: Assume all full binary trees of height h, 0 < h <= H have 2 h leaf nodes. For a FBT, T, of height H, create a new FBT T' by adding exactly two children to each leaf of T . The height of T' is H + 1 and T' has twice the nuber of leaf nodes as T , namely 2 X 2H = 2 H+1.

Theorem 32.3 The number of nodes in a full binary tree of height h is 2 h+1 - 1 Proof: The number of nodes is the sum of the number of nodes on each level, l. Since there are 2l nodes at each level, the total number of nodes is

SUMht=0 2t = 2h+1 - 1
The equation is easily proven by induction.

Theorem 32.4 If n is the number of nodes in a complete binary tree (CBT) of height h, then 2h <= n < 2h+1 Proof: A CBT of height h has at least one and as many as 2h nodes at level h (the final level is not empty, and may be full). In any event, level h - 1, (h > 0) ,must be full by definition of a CBT. The number of nodes in a FBT of height h - 1 is 2(h - 1) + 1 - 1. (By Theorem 32.3 above) A CBT of height h has at least one more node than a FBT of height h - 1. Therefore, the number of nodes n in a CBT is bounded by
2(h - 1) + 1 - 1 + 1 <= n <= 2h+1 - 1 Therefore, 2h <= n < 2h+1 Equivalently, we can say h <= lg n < h + 1.

Rooted Tree

A rooted tree is a tree in which a special ("labeled") node is singled out. This node is called the "root" or (less commonly) "eve" of the tree. Rooted trees are equivalent to oriented trees (Knuth 1997, pp. 385-399). A tree which is not rooted is sometimes called a free tree, although the unqualified term "tree" generally refers to a free tree. A rooted tree in which the root node has vertex degree 1 is known as a planted tree. The numbers of rooted trees on nodes for , 2, ... are 1, 1, 2, 4, 9, 20, 48, 115, 286, 719, 1842, 4766, ... nodes by , then the generating function is

(Sloane's A000081). Denote the number of rooted trees with

(1)

(2)

This power series satisfies (3)

(4)

where is the generating function for unrooted trees. A generating function for involving the sequence itself as

can be written using a product

(5)

The number of rooted trees can also be calculated from the recurrence relation (6)

with

and

, where the second sum is over all

which divide (Finch 2003).

As shown by Otter (1948), (7)

(8)

(Sloane's A051491; Odlyzko 1995; Knuth 1997, p. 396), where

is given by the unique positive root of (9)

If

is the number of nonisomorphic rooted trees on

nodes, then an asymptotic series for

is given by

(10)

where the constants can be computed in terms of partial derivatives of the function (11)

(Plotkin and Rosenthal 1994; Finch 2003).


SEE ALSO: Free Tree, Ordered Tree, Planted Tree, Red-Black Tree, Rooted Graph, Tree, Weakly Binary Tree REFERENCES: Borwein, J. and Bailey, D. Mathematics by Experiment: Plausible Reasoning in the 21st Century. Wellesley, MA: A K Peters, p. 22, 2003. Finch, S. R. "Otter's Tree Enumeration Constants." 5.6 in Mathematical Constants. Cambridge, England: Cambridge University Press, pp. 295-316, 2003. Finch, S. "Two Asymptotic Series." December 10, 2003. http://algo.inria.fr/bsolve/. Harary, F. Graph Theory. Reading, MA: Addison-Wesley, pp. 187-190 and 232, 1994. Harary, F. and Palmer, E. M. "Rooted Trees." 3.1 in Graphical Enumeration. New York: Academic Press, pp. 51-54, 1973. Knuth, D. E. The Art of Computer Programming, Vol. 1: Fundamental Algorithms, 3rd ed. Reading, MA: Addison-Wesley, 1997. Nijenhuis, A. and Wilf, H. Combinatorial Algorithms for Computers and Calculators, 2nd ed. New York: Academic Press, 1978. Odlyzko, A. M. "Asymptotic Enumeration Methods." In Handbook of Combinatorics, Vol. 2 (Ed. R. L. Graham, M. Grtschel, and L. Lovsz). Cambridge, MA: MIT Press, pp. 1063-1229, 1995. http://www.dtc.umn.edu/~odlyzko/doc/asymptotic.enum.pdf. Otter, R. "The Number of Trees." Ann. Math. 49, 583-599, 1948. Plotkin, J. M. and Rosenthal, J. W. "How to Obtain an Asymptotic Expansion of a Sequence from an Analytic Identity Satisfied by Its Generating Function." J. Austral. Math. Soc. Ser. A 56, 131-143, 1994. Plya, G. "On Picture-Writing." Amer. Math. Monthly 63, 689-697, 1956. Ruskey, F. "Information on Rooted Trees." http://www.theory.csc.uvic.ca/~cos/inf/tree/RootedTree.html. Sloane, N. J. A. Sequences A000081/M1180 and A051491 in "The On-Line Encyclopedia of Integer Sequences." Wilf, H. S. Combinatorial Algorithms: An Update. Philadelphia, PA: SIAM, 1989.

Information on Rooted Trees

A rooted tree may be defined as a free tree in which some node has been distinguished as the root. Above we show a list of all 9 rooted trees on 5 vertices. Roots are shown in blue. A rooted tree may be regarded as an equivalence class of ordered trees. Two ordered trees are equivalent if one may be transformed into the other by re-ordering subtrees. In the figure above the number of ordered trees in the equivalence class of each rooted tree is 1, 1, 2, 2, 1, 2, 1, 3, 1, respectively. The sum of these numbers is 14, the 5th Catalan number and the number of ordered trees on 5 nodes. One natural way of encoding an ordered tree is to record the parent of each node in preorder. In the figure on the left each node points to its parent. Taking 0 to be the parent of the root, the sequence obtained is 0121156685. This is called the parent array. Another way of encoding an ordered tree is to record the level (distance from the root) at which its nodes occur in preorder. In the tree shown on the right the numbers give a preorder labelling and by recording the level number of those nodes we obtain the sequence 0121123342. This is called the level sequence.

The two trees shown above are the same when regarded as unlabelled rooted trees, since one may be obtained from the other by reordering subtrees. Among all ordered trees that are equivalent we choose the one whose parent array is lexicographically largest (i.e., biggest when regarded as a number) and call it canonic. By generating canonic ordered trees, we generate all rooted trees. The second tree illustrated is canonic (the one with parent array 0123432181). Intuitively, we transform an ordered tree into a canonic tree by recursively pushing subtrees with greater height to the left. The list of all trees with 5 nodes shown at the top of this page shows the canonic tree from each equivalence class. For n = 1,2,3,...,15 the number of rooted trees is 1, 1, 2, 4, 9, 20, 48, 115, 286, 719, 1842, 4766, 12486, 32973, 87811. This is sequence A000081(M1180) in Neil J. Sloane's database of integer sequences.

Binary Rooted Trees

An important subclass of the rooted trees are the those in which every node has either two children or is a leaf (has no children). These trees are output by the program by setting m = 2

(giving the list shown above), and then by adding n+1 leaves to the resulting trees, as shown below.

The number of binary rooted trees with n = 1,2,3,...,15 internal nodes is 1, 1, 2, 3, 6, 11, 23, 46, 98, 207, 451, 983, 2179, 4850, 10905, respectively. This is sequence A001190(M0790) in Neil J. Sloane's database of integer sequences. Rooted trees where each node has at most 3 children are sometimes called quartic planted trees. For n = 1,2,3,...,15 internal nodes, there are 1, 1, 2, 4, 8, 17, 39, 89, 211, 507, 1238, 3057, 7639, 19241, 48865 of them, respectively. This is sequence A000598(M1146) in Neil J. Sloane's database of integer sequences. Rooted trees where each node has at most 4 children are counted for n = 1,2,3,...,20 nodes, by the numbers 1, 1, 2, 4, 9, 19, 45, 106, 260, 643, 1624, 4138, 10683, 27790, 72917, 192548, 511624, 1366424, 3666930, 9881527, respectively. This is sequence A036718 in Neil J. Sloane's database of integer sequences. The asymptotic number of binary rooted trees has been studied by Otter and others. You may click here for further information.

Counts of rooted trees classified by height


n 1 2 1 21 31 41 51 1 2 4 1 3 8 18 38 76 1 4 13 36 93 225 1 5 19 61 180 1 6 26 94 1 7 34 1 8 1 3 4 5 6 7 8 9 10 11 12 13 14 15

61 6 7 1 10 8 1 14 9 1 21

10 1 29 147

11 1 41 277 528 498 12 1 55 509 1198 1323

308 941

136

43

9 53

1 10 1

487 188

13 1 76 924 2666 3405 2744 1615 728 251 64 11 1 14 1 100 1648 5815 8557 7722 5079 2593 1043 326 76 12 1 15 1 134 2912 12517 21103 21166 15349 8706 3961 1445 414 89 13 1 The sum of the first two columns is the number of numerical partitions of n+1. The sum of the first three columns is Sloane's A001383(M1107). The sum of the first four columns is Sloane's A001384(M1172).

COS options
In COS the user can output the parent array (standard representation) or the level sequence (alternate representation). An upper bound on the number of children of a node can be specified (as m). Upper and lower bounds on the height can also be specified (as lb and ub). The algorithm used in COS is from Gang Li and Frank Ruskey, The Advantages of Forward Thinking in Generating Rooted and Free Trees, 10th Annual ACM-SIAM Symposium on Discrete Algorithms (SODA), (1999) S939-940.

Number of Rooted and Unrooted Trees


Number of unrooted trees for n taxa Nu=(2n-5)*(2n-7)*...*3*1=(2n-5)!/[2n-3*(n-3)!] Number of rooted trees for n taxa Nr=(2n-3)*(2n-5)*(2n-7)*...*3*1=(2n-3)!/[2n-2*(n-2)!] Note that the number of unrooted trees for n sequences is equal for the number of rooted trees for (n-1) sequences. Number of Taxa 3 4 5 6 7 8 Number of unrooted trees 1 3 15 105 945 10395 Number of rooted trees 3 15 105 945 10395 135135

Number of Taxa 9 10 20 30 40 50 60 70 80

Number of unrooted trees 135135 2027025 2.22E+020 8.69E+036 1.31E+055 2.84E+074 5.01E+094 5.00E+115 2.18E+137

Number of rooted trees 2027025 34459425 8.20E+021 4.95E+038 1.01E+057 2.75E+076 5.86E+096 6.85E+117 3.43E+139

For comparison the universe contains only about 1089 protons and has an age of about 5*1017 seconds or 5*1029 picoseconds.

Binary tree
From Wikipedia, the free encyclopedia Jump to: navigation, search Not to be confused with B-tree.

A simple binary tree of size 9 and depth 3, with a root node whose value is 2. The above tree is unbalanced and not sorted.

In computer science, a binary tree is a tree data structure in which each node has at most two child nodes, usually distinguished as "left" and "right". Nodes with children are parent nodes, and child nodes may contain references to their parents. Outside the tree, there is often a reference to the "root" node (the ancestor of all nodes), if it exists. Any node in the data structure can be reached by starting at root node and repeatedly following references to either the left or right child. Binary trees are used to implement binary search trees and binary heaps.

Contents
[hide]

1 Definitions for rooted trees 2 Types of binary trees 3 Properties of binary trees 4 Common operations o 4.1 Insertion 4.1.1 External nodes 4.1.2 Internal nodes o 4.2 Deletion 4.2.1 Node with zero or one children 4.2.2 Node with two children o 4.3 Iteration 4.3.1 Pre-order, in-order, and post-order traversal 4.3.2 Depth-first order 4.3.3 Breadth-first order 5 Type theory 6 Definition in graph theory 7 Combinatorics 8 Methods for storing binary trees o 8.1 Nodes and references o 8.2 Arrays 9 Encodings o 9.1 Succinct encodings o 9.2 Encoding general trees as binary trees 10 See also 11 Notes 12 References 13 External links

[edit] Definitions for rooted trees

A directed edge refers to the link from the parent to the child (the arrows in the picture of the tree).

The root node of a tree is the node with no parents. There is at most one root node in a rooted tree. A leaf node has no children. The depth of a node n is the length of the path from the root to the node. The set of all nodes at a given depth is sometimes called a level of the tree. The root node is at depth zero. The depth (or height) of a tree is the length of the path from the root to the deepest node in the tree. A (rooted) tree with only one node (the root) has a depth of zero. Siblings are nodes that share the same parent node. A node p is an ancestor of a node q if it exists on the path from the root to node q. The node q is then termed as a descendant of p. The size of a node is the number of descendants it has including itself. In-degree of a node is the number of edges arriving at that node. Out-degree of a node is the number of edges leaving that node. The root is the only node in the tree with In-degree = 0. All the leaf nodes have Out-degree = 0.

[edit] Types of binary trees


A rooted binary tree is a tree with a root node in which every node has at most two children. A full binary tree (sometimes proper binary tree or 2-tree or strictly binary tree) is a tree in which every node other than the leaves has two children. Sometimes a full tree is ambiguously defined as a perfect tree. A perfect binary tree is a full binary tree in which all leaves are at the same depth or same level, and in which every parent has two children.[1] (This is ambiguously also called a complete binary tree.) A complete binary tree is a binary tree in which every level, except possibly the last, is completely filled, and all nodes are as far left as possible.[2] An infinite complete binary tree is a tree with a countably infinite number of levels, in which every node has two children, so that there are 2d nodes at level d. The set of all nodes is countably infinite, but the set of all infinite paths from the root is uncountable: it has the cardinality of the continuum. These paths corresponding by an order preserving bijection to the points of the Cantor set, or (through the example of the SternBrocot tree) to the set of positive irrational numbers. A balanced binary tree is commonly defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1,[3] although in general it is a binary tree where no leaf is much farther away from the root than any other leaf. (Different balancing schemes allow different definitions of "much farther"[4]). Binary trees that are balanced according to this definition have a predictable depth (how many nodes are traversed from the root to a leaf, root counting as node 0 and subsequent as 1, 2, ..., depth). This depth is equal to the integer part of balanced tree with 1 node, where is the number of nodes on the balanced tree. Example 1: (depth = 0). Example 2: balanced tree with 3 nodes,

(depth=1). Example 3: balanced tree with 5 nodes, (depth of tree is 2 nodes). A rooted complete binary tree can be identified with a free magma.

A degenerate tree is a tree where for each parent node, there is only one associated child node. This means that in a performance measurement, the tree will behave like a linked list data structure.

Note that this terminology often varies in the literature, especially with respect to the meaning "complete" and "full".

[edit] Properties of binary trees


The number of nodes

in a perfect binary tree can be found using this formula: and at most

where is the depth of the tree. The number of nodes in a complete binary tree is at least

where is the depth of the tree. The number of leaf nodes in a perfect binary tree can be found using this formula: where is the depth of the tree. The number of nodes in a perfect binary tree can also be found using this formula: where is the number of leaf nodes in the tree. The number of null links (absent children of nodes) in a complete binary tree of n nodes is (n+1). The number nL of internal nodes (non-leaf nodes) in a Complete Binary Tree of n nodes is . For any non-empty binary tree with n0 leaf nodes and n2 nodes of degree 2, n0 = n2 + 1.[5] Proof: Let n = the total number of nodes B = number of branches n0, n1, n2 represent the number of nodes with no children, a single child, and two children respectively. B = n - 1 (since all nodes except the root node come from a single branch) B = n1 + 2*n2 n = n1+ 2*n2 + 1 n = n0 + n1 + n2 n1+ 2*n2 + 1 = n0 + n1 + n2 ==> n0 = n2 + 1

[edit] Common operations


There are a variety of different operations that can be performed on binary trees. Some are mutator operations, while others simply return useful information about the tree.

[edit] Insertion
Nodes can be inserted into binary trees in between two other nodes or added after an external node. In binary trees, a node that is inserted is specified as to which child it is.
[edit] External nodes

Say that the external node being added on to is node A. To add a new node after node A, A assigns the new node as one of its children and the new node assigns node A as its parent.
[edit] Internal nodes

The process of inserting a node into a binary tree

Insertion on internal nodes is slightly more complex than on external nodes. Say that the internal node is node A and that node B is the child of A. (If the insertion is to insert a right child, then B is the right child of A, and similarly with a left child insertion.) A assigns its child to the new node and the new node assigns its parent to A. Then the new node assigns its child to B and B assigns its parent as the new node.

[edit] Deletion
Deletion is the process whereby a node is removed from the tree. Only certain nodes in a binary tree can be removed unambiguously.[6]
[edit] Node with zero or one children

The process of deleting an internal node in a binary tree

Say that the node to delete is node A. If a node has no children (external node), deletion is accomplished by setting the child of A's parent to null. If it has one child, set the parent of A's child to A's parent and set the child of A's parent to A's child.
[edit] Node with two children

In a binary tree, a node with two children cannot be deleted unambiguously.[6] However, in certain binary trees these nodes can be deleted, including binary search trees.

[edit] Iteration
Often, one wishes to visit each of the nodes in a tree and examine the value there, a process called iteration or enumeration. There are several common orders in which the nodes can be visited, and each has useful properties that are exploited in algorithms based on binary trees:

Pre-Order: Root first, Left child, Right child Post-Order: Left Child, Right child, root In-Order: Left child, root, right child.

[edit] Pre-order, in-order, and post-order traversal Main article: Tree traversal

Pre-order, in-order, and post-order traversal visit each node in a tree by recursively visiting each node in the left and right subtrees of the root.
[edit] Depth-first order

In depth-first order, we always attempt to visit the node farthest from the root that we can, but with the caveat that it must be a child of a node we have already visited. Unlike a depth-first search on graphs, there is no need to remember all the nodes we have visited, because a tree cannot contain cycles. Pre-order is a special case of this. See depth-first search for more information.
[edit] Breadth-first order

Contrasting with depth-first order is breadth-first order, which always attempts to visit the node closest to the root that it has not already visited. See breadth-first search for more information. Also called a level-order traversal.

[edit] Type theory


In type theory, a binary tree with nodes of type A is defined inductively as TA = . 1 + A .

[edit] Definition in graph theory

For each binary tree data structure, there is equivalent rooted binary tree in graph theory. Graph theorists use the following definition: A binary tree is a connected acyclic graph such that the degree of each vertex is no more than three. It can be shown that in any binary tree of two or more nodes, there are exactly two more nodes of degree one than there are of degree three, but there can be any number of nodes of degree two. A rooted binary tree is such a graph that has one of its vertices of degree no more than two singled out as the root. With the root thus chosen, each vertex will have a uniquely defined parent, and up to two children; however, so far there is insufficient information to distinguish a left or right child. If we drop the connectedness requirement, allowing multiple connected components in the graph, we call such a structure a forest. Another way of defining binary trees is a recursive definition on directed graphs. A binary tree is either:

A single vertex. A graph formed by taking two binary trees, adding a vertex, and adding an edge directed from the new vertex to the root of each binary tree.

This also does not establish the order of children, but does fix a specific root node.

[edit] Combinatorics
In combinatorics one considers the problem of counting the number of full binary trees of a given size. Here the trees have no values attached to their nodes (this would just multiply the number of possible trees by an easily determined factor), and trees are distinguished only by their structure; however the left and right child of any node are distinguished (if they are different trees, then interchanging them will produce a tree distinct from the original one). The size of the tree is taken to be the number n of internal nodes (those with two children); the other nodes are leaf nodes and there are n + 1 of them. The number of such binary trees of size n is equal to the number of ways of fully parenthesizing a string of n + 1 symbols (representing leaves) separated by n binary operators (representing internal nodes), so as to determine the argument subexpressions of each operator. For instance for n = 3 one has to parenthesize a string like , which is possible in five ways:

The correspondence to binary trees should be obvious, and the addition of redundant parentheses (around an already parenthesized expression or around the full expression) is disallowed (or at least not counted as producing a new possibility). There is a unique binary tree of size 0 (consisting of a single leaf), and any other binary tree is characterized by the pair of its left and right children; if these have sizes i and j respectively, the full tree has size i + j + 1. Therefore the number of binary trees of size n has the following

recursive description , and follows that is the Catalan number of index n.

for any positive integer n. It

The above parenthesized strings should not be confused with the set of words of length 2n in the Dyck language, which consist only of parentheses in such a way that they are properly balanced. The number of such strings satisfies the same recursive description (each Dyck word of length 2n is determined by the Dyck subword enclosed by the initial '(' and its matching ')' together with the Dyck subword remaining after that closing parenthesis, whose lengths 2i and 2j satisfy i + j + 1 = n); this number is therefore also the Catalan number . So there are also five Dyck words of length 10:
.

These Dyck words do not correspond in an obvious way to binary trees. A bijective correspondence can nevertheless be defined as follows: enclose the Dyck word in a extra pair of parentheses, so that the result can be interpreted as a Lisp list expression (with the empty list () as only occurring atom); then the dotted-pair expression for that proper list is a fully parenthesized expression (with NIL as symbol and '.' as operator) describing the corresponding binary tree (which is in fact the internal representation of the proper list). The ability to represent binary trees as strings of symbols and parentheses implies that binary trees can represent the elements of a free magma on a singleton set.

[edit] Methods for storing binary trees


Binary trees can be constructed from programming language primitives in several ways.

[edit] Nodes and references


In a language with records and references, binary trees are typically constructed by having a tree node structure which contains some data and references to its left child and its right child. Sometimes it also contains a reference to its unique parent. If a node has fewer than two children, some of the child pointers may be set to a special null value, or to a special sentinel node. In languages with tagged unions such as ML, a tree node is often a tagged union of two types of nodes, one of which is a 3-tuple of data, left child, and right child, and the other of which is a "leaf" node, which contains no data and functions much like the null value in a language with pointers.

[edit] Arrays
Binary trees can also be stored in breadth-first order as an implicit data structure in arrays, and if the tree is a complete binary tree, this method wastes no space. In this compact arrangement, if a node has an index i, its children are found at indices (for the left child) and (for

the right), while its parent (if any) is found at index (assuming the root has index zero). This method benefits from more compact storage and better locality of reference, particularly during a preorder traversal. However, it is expensive to grow and wastes space proportional to 2h - n for a tree of depth h with n nodes. This method of storage is often used for binary heaps. No space is wasted because nodes are added in breadth-first order.

[edit] Encodings
[edit] Succinct encodings
A succinct data structure is one which takes the absolute minimum possible space, as established by information theoretical lower bounds. The number of different binary trees on nodes is , the th Catalan number (assuming we view trees with identical structure as identical). For large , this is about ; thus we need at least about bits to encode it. A succinct binary tree therefore would occupy only 2 bits per node. One simple representation which meets this bound is to visit the nodes of the tree in preorder, outputting "1" for an internal node and "0" for a leaf. [1] If the tree contains data, we can simply simultaneously store it in a consecutive array in preorder. This function accomplishes this:
function EncodeSuccinct(node n, bitstring structure, array data) { if n = nil then append 0 to structure; else append 1 to structure; append n.data to data; EncodeSuccinct(n.left, structure, data); EncodeSuccinct(n.right, structure, data); }

The string structure has only bits in the end, where is the number of (internal) nodes; we don't even have to store its length. To show that no information is lost, we can convert the output back to the original tree like this:
function DecodeSuccinct(bitstring structure, array data) { remove first bit of structure and put it in b if b = 1 then create a new node n remove first element of data and put it in n.data

n.left = DecodeSuccinct(structure, data) n.right = DecodeSuccinct(structure, data) return n else return nil }

More sophisticated succinct representations allow not only compact storage of trees but even useful operations on those trees directly while they're still in their succinct form. The above program only works for a full binary tree.(i.e. each node is either a leaf or has at least 2 children).

[edit] Encoding general trees as binary trees


There is a one-to-one mapping between general ordered trees and binary trees, which in particular is used by Lisp to represent general ordered trees as binary trees. To convert a general ordered tree to binary tree, we only need to represent the general tree in left child-sibling way. The result of this representation will be automatically binary tree, if viewed from a different perspective. Each node N in the ordered tree corresponds to a node N' in the binary tree; the left child of N' is the node corresponding to the first child of N, and the right child of N' is the node corresponding to N 's next sibling --- that is, the next node in order among the children of the parent of N. This binary tree representation of a general order tree is sometimes also referred to as a left child-right sibling binary tree (LCRS tree), or a doubly chained tree, or a Filial-Heir chain. One way of thinking about this is that each node's children are in a linked list, chained together with their right fields, and the node only has a pointer to the beginning or head of this list, through its left field. For example, in the tree on the left, A has the 6 children {B,C,D,E,F,G}. It can be converted into the binary tree on the right.

The binary tree can be thought of as the original tree tilted sideways, with the black left edges representing first child and the blue right edges representing next sibling. The leaves of the tree on the left would be written in Lisp as:
(((N O) I J) C D ((P) (Q)) F (M))

which would be implemented in memory as the binary tree on the right, without any letters on those nodes that have a left child.

[edit] See also


2-3 tree 2-3-4 tree AA tree B-tree Binary space partitioning Elastic binary tree Huffman tree Kraft's inequality Random binary tree Recursion (computer science) Red-black tree Rope (computer science) Self-balancing binary search tree Strahler number Threaded binary Tree of primitive Pythagorean triples Alternative methods of generating the tree # Unrooted binary tree

[edit] Notes
1. 2. 3. 4. 5. 6. ^ "perfect binary tree". NIST. http://www.nist.gov/dads/HTML/perfectBinaryTree.html. ^ "complete binary tree". NIST. http://www.nist.gov/dads/HTML/completeBinaryTree.html. ^ Aaron M. Tenenbaum, et. al Data Structures Using C, Prentice Hall, 1990 ISBN 0-13-199746-7 ^ Paul E. Black (ed.), entry for data structure in Dictionary of Algorithms and Data Structures. U.S. National Institute of Standards and Technology. 15 December 2004. Online version Accessed 2010-12-19. ^ Mehta, Dinesh; Sartaj Sahni (2004). Handbook of Data Structures and Applications. Chapman and Hall. ISBN 1584884355. ab ^ Dung X. Nguyen (2003). "Binary Tree Structure". rice.edu. http://www.clear.rice.edu/comp212/03spring/lectures/22/. Retrieved December 28, 2010.

[edit] References

Donald Knuth. The art of computer programming vol 1. Fundamental Algorithms, Third Edition. Addison-Wesley, 1997. ISBN 0-201-89683-4. Section 2.3, especially subsections 2.3.12.3.2 (pp. 318348).

Kenneth A Berman, Jerome L Paul. Algorithms: Parallel, Sequential and Distributed. Course Technology, 2005. ISBN 0-534-42057-5. Chapter 4. (pp. 113166).

[edit] External links


flash actionscript 3 opensource implementation of binary tree opensource library [2] GameDev.net's article about binary trees [3] Binary Tree Proof by Induction Balanced binary search tree on array How to create bottom-up an Ahnentafel list, or a balanced binary search tree on array [hide]

v t e

Trees in computer science


Binary trees

Binary search tree (BST) Cartesian tree Top tree T-tree AA tree AVL tree LLRB tree Redblack tree Scapegoat tree Splay tree Treap B+ tree B*-tree Bx-tree UB-tree 2-3 tree 2-3-4 tree (a,b)-tree Dancing tree Htree Suffix tree Radix tree Ternary search tree

Self-balancing binary search trees

B-trees

Tries

X-fast trie Y-fast trie Quadtree Octree k-d tree Implicit k-d tree vp-tree Exponential tree Fusion tree Interval tree PQ tree Range tree SPQR tree Van Emde Boas tree R-tree R+ tree R* tree X-tree M-tree Segment tree Hilbert R-tree Priority R-tree Heap Hash tree Finger tree Metric tree Cover tree BK-tree Doubly-chained tree iDistance Link-cut tree Fenwick tree

Binary space partitioning (BSP) trees

Non-binary trees

Spatial data partitioning trees

Other trees

Retrieved from "http://en.wikipedia.org/w/index.php?title=Binary_tree&oldid=484739303" View page ratings

Rate this page


What's this? Trustworthy

Objective

Complete

Well-written

I am highly knowledgeable about this topic (optional) Submit ratings Saved successfully Your ratings have not been submitted yet Categories:

Binary trees Data structures

Personal tools

Log in / create account

Namespaces

Article Talk

Variants Views Actions Search

Read Edit View history

Search

Special:Search

Navigation

Main page Contents Featured content Current events Random article Donate to Wikipedia

Interaction Toolbox

Help About Wikipedia Community portal Recent changes Contact Wikipedia

What links here Related changes Upload file Special pages Permanent link Cite this page Rate this page

Print/export

Create a book Download as PDF Printable version

Languages

Catal esky Deutsch Espaol Esperanto Franais

Bahasa Indonesia slenska Italiano

Polski Portugus Romn Slovenina Slovenina / Srpski Suomi Svenska This page was last modified on 30 March 2012 at 19:10. Text is available under the Creative Commons Attribution-ShareAlike License; additional terms may apply. See Terms of use for details. Wikipedia is a registered trademark of the Wikimedia Foundation, Inc., a non-profit organization. Contact us Privacy policy About Wikipedia Disclaimers Mobile view

Binary tree
From Wikipedia, the free encyclopedia Jump to: navigation, search Not to be confused with B-tree.

A simple binary tree of size 9 and depth 3, with a root node whose value is 2. The above tree is unbalanced and not sorted.

In computer science, a binary tree is a tree data structure in which each node has at most two child nodes, usually distinguished as "left" and "right". Nodes with children are parent nodes, and child nodes may contain references to their parents. Outside the tree, there is often a reference to the "root" node (the ancestor of all nodes), if it exists. Any node in the data structure can be reached by starting at root node and repeatedly following references to either the left or right child. Binary trees are used to implement binary search trees and binary heaps.

Contents
[hide]

1 Definitions for rooted trees 2 Types of binary trees 3 Properties of binary trees 4 Common operations o 4.1 Insertion 4.1.1 External nodes 4.1.2 Internal nodes o 4.2 Deletion 4.2.1 Node with zero or one children 4.2.2 Node with two children o 4.3 Iteration 4.3.1 Pre-order, in-order, and post-order traversal 4.3.2 Depth-first order 4.3.3 Breadth-first order 5 Type theory 6 Definition in graph theory 7 Combinatorics 8 Methods for storing binary trees

8.1 Nodes and references 8.2 Arrays 9 Encodings o 9.1 Succinct encodings o 9.2 Encoding general trees as binary trees 10 See also 11 Notes 12 References 13 External links

o o

[edit] Definitions for rooted trees


A directed edge refers to the link from the parent to the child (the arrows in the picture of the tree). The root node of a tree is the node with no parents. There is at most one root node in a rooted tree. A leaf node has no children. The depth of a node n is the length of the path from the root to the node. The set of all nodes at a given depth is sometimes called a level of the tree. The root node is at depth zero. The depth (or height) of a tree is the length of the path from the root to the deepest node in the tree. A (rooted) tree with only one node (the root) has a depth of zero. Siblings are nodes that share the same parent node. A node p is an ancestor of a node q if it exists on the path from the root to node q. The node q is then termed as a descendant of p. The size of a node is the number of descendants it has including itself. In-degree of a node is the number of edges arriving at that node. Out-degree of a node is the number of edges leaving that node. The root is the only node in the tree with In-degree = 0. All the leaf nodes have Out-degree = 0.

[edit] Types of binary trees


A rooted binary tree is a tree with a root node in which every node has at most two children. A full binary tree (sometimes proper binary tree or 2-tree or strictly binary tree) is a tree in which every node other than the leaves has two children. Sometimes a full tree is ambiguously defined as a perfect tree. A perfect binary tree is a full binary tree in which all leaves are at the same depth or same level, and in which every parent has two children.[1] (This is ambiguously also called a complete binary tree.) A complete binary tree is a binary tree in which every level, except possibly the last, is completely filled, and all nodes are as far left as possible.[2] An infinite complete binary tree is a tree with a countably infinite number of levels, in which every node has two children, so that there are 2d nodes at level d. The set of all nodes is countably infinite, but the set of all infinite paths from the root is uncountable: it has the cardinality of the continuum. These paths corresponding by an order preserving bijection to the

points of the Cantor set, or (through the example of the SternBrocot tree) to the set of positive irrational numbers. A balanced binary tree is commonly defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1,[3] although in general it is a binary tree where no leaf is much farther away from the root than any other leaf. (Different balancing schemes allow different definitions of "much farther"[4]). Binary trees that are balanced according to this definition have a predictable depth (how many nodes are traversed from the root to a leaf, root counting as node 0 and subsequent as 1, 2, ..., depth). This depth is equal to the integer part of balanced tree with 1 node, where is the number of nodes on the balanced tree. Example 1: (depth = 0). Example 2: balanced tree with 3 nodes,

(depth=1). Example 3: balanced tree with 5 nodes, (depth of tree is 2 nodes). A rooted complete binary tree can be identified with a free magma. A degenerate tree is a tree where for each parent node, there is only one associated child node. This means that in a performance measurement, the tree will behave like a linked list data structure.

Note that this terminology often varies in the literature, especially with respect to the meaning "complete" and "full".

[edit] Properties of binary trees


The number of nodes

in a perfect binary tree can be found using this formula: and at most

where is the depth of the tree. The number of nodes in a complete binary tree is at least

where is the depth of the tree. The number of leaf nodes in a perfect binary tree can be found using this formula: where is the depth of the tree. The number of nodes in a perfect binary tree can also be found using this formula: where is the number of leaf nodes in the tree. The number of null links (absent children of nodes) in a complete binary tree of n nodes is (n+1). The number nL of internal nodes (non-leaf nodes) in a Complete Binary Tree of n nodes is . For any non-empty binary tree with n0 leaf nodes and n2 nodes of degree 2, n0 = n2 + 1.[5] Proof: Let n = the total number of nodes B = number of branches n0, n1, n2 represent the number of nodes with no children, a single child, and two children respectively. B = n - 1 (since all nodes except the root node come from a single branch)

B = n1 + 2*n2 n = n1+ 2*n2 + 1 n = n0 + n1 + n2 n1+ 2*n2 + 1 = n0 + n1 + n2 ==> n0 = n2 + 1

[edit] Common operations


There are a variety of different operations that can be performed on binary trees. Some are mutator operations, while others simply return useful information about the tree.

[edit] Insertion
Nodes can be inserted into binary trees in between two other nodes or added after an external node. In binary trees, a node that is inserted is specified as to which child it is.
[edit] External nodes

Say that the external node being added on to is node A. To add a new node after node A, A assigns the new node as one of its children and the new node assigns node A as its parent.
[edit] Internal nodes

The process of inserting a node into a binary tree

Insertion on internal nodes is slightly more complex than on external nodes. Say that the internal node is node A and that node B is the child of A. (If the insertion is to insert a right child, then B is the right child of A, and similarly with a left child insertion.) A assigns its child to the new node and the new node assigns its parent to A. Then the new node assigns its child to B and B assigns its parent as the new node.

[edit] Deletion
Deletion is the process whereby a node is removed from the tree. Only certain nodes in a binary tree can be removed unambiguously.[6]

[edit] Node with zero or one children

The process of deleting an internal node in a binary tree

Say that the node to delete is node A. If a node has no children (external node), deletion is accomplished by setting the child of A's parent to null. If it has one child, set the parent of A's child to A's parent and set the child of A's parent to A's child.
[edit] Node with two children

In a binary tree, a node with two children cannot be deleted unambiguously.[6] However, in certain binary trees these nodes can be deleted, including binary search trees.

[edit] Iteration
Often, one wishes to visit each of the nodes in a tree and examine the value there, a process called iteration or enumeration. There are several common orders in which the nodes can be visited, and each has useful properties that are exploited in algorithms based on binary trees:

Pre-Order: Root first, Left child, Right child Post-Order: Left Child, Right child, root In-Order: Left child, root, right child.

[edit] Pre-order, in-order, and post-order traversal Main article: Tree traversal

Pre-order, in-order, and post-order traversal visit each node in a tree by recursively visiting each node in the left and right subtrees of the root.
[edit] Depth-first order

In depth-first order, we always attempt to visit the node farthest from the root that we can, but with the caveat that it must be a child of a node we have already visited. Unlike a depth-first search on graphs, there is no need to remember all the nodes we have visited, because a tree cannot contain cycles. Pre-order is a special case of this. See depth-first search for more information.

[edit] Breadth-first order

Contrasting with depth-first order is breadth-first order, which always attempts to visit the node closest to the root that it has not already visited. See breadth-first search for more information. Also called a level-order traversal.

[edit] Type theory


In type theory, a binary tree with nodes of type A is defined inductively as TA = . 1 + A .

[edit] Definition in graph theory


For each binary tree data structure, there is equivalent rooted binary tree in graph theory. Graph theorists use the following definition: A binary tree is a connected acyclic graph such that the degree of each vertex is no more than three. It can be shown that in any binary tree of two or more nodes, there are exactly two more nodes of degree one than there are of degree three, but there can be any number of nodes of degree two. A rooted binary tree is such a graph that has one of its vertices of degree no more than two singled out as the root. With the root thus chosen, each vertex will have a uniquely defined parent, and up to two children; however, so far there is insufficient information to distinguish a left or right child. If we drop the connectedness requirement, allowing multiple connected components in the graph, we call such a structure a forest. Another way of defining binary trees is a recursive definition on directed graphs. A binary tree is either:

A single vertex. A graph formed by taking two binary trees, adding a vertex, and adding an edge directed from the new vertex to the root of each binary tree.

This also does not establish the order of children, but does fix a specific root node.

[edit] Combinatorics
In combinatorics one considers the problem of counting the number of full binary trees of a given size. Here the trees have no values attached to their nodes (this would just multiply the number of possible trees by an easily determined factor), and trees are distinguished only by their structure; however the left and right child of any node are distinguished (if they are different trees, then interchanging them will produce a tree distinct from the original one). The size of the tree is taken to be the number n of internal nodes (those with two children); the other nodes are leaf nodes and there are n + 1 of them. The number of such binary trees of size n is equal to the number of ways of fully parenthesizing a string of n + 1 symbols (representing leaves) separated

by n binary operators (representing internal nodes), so as to determine the argument subexpressions of each operator. For instance for n = 3 one has to parenthesize a string like , which is possible in five ways:

The correspondence to binary trees should be obvious, and the addition of redundant parentheses (around an already parenthesized expression or around the full expression) is disallowed (or at least not counted as producing a new possibility). There is a unique binary tree of size 0 (consisting of a single leaf), and any other binary tree is characterized by the pair of its left and right children; if these have sizes i and j respectively, the full tree has size i + j + 1. Therefore the number of binary trees of size n has the following recursive description , and follows that is the Catalan number of index n. for any positive integer n. It

The above parenthesized strings should not be confused with the set of words of length 2n in the Dyck language, which consist only of parentheses in such a way that they are properly balanced. The number of such strings satisfies the same recursive description (each Dyck word of length 2n is determined by the Dyck subword enclosed by the initial '(' and its matching ')' together with the Dyck subword remaining after that closing parenthesis, whose lengths 2i and 2j satisfy i + j + 1 = n); this number is therefore also the Catalan number . So there are also five Dyck words of length 10:
.

These Dyck words do not correspond in an obvious way to binary trees. A bijective correspondence can nevertheless be defined as follows: enclose the Dyck word in a extra pair of parentheses, so that the result can be interpreted as a Lisp list expression (with the empty list () as only occurring atom); then the dotted-pair expression for that proper list is a fully parenthesized expression (with NIL as symbol and '.' as operator) describing the corresponding binary tree (which is in fact the internal representation of the proper list). The ability to represent binary trees as strings of symbols and parentheses implies that binary trees can represent the elements of a free magma on a singleton set.

[edit] Methods for storing binary trees


Binary trees can be constructed from programming language primitives in several ways.

[edit] Nodes and references


In a language with records and references, binary trees are typically constructed by having a tree node structure which contains some data and references to its left child and its right child.

Sometimes it also contains a reference to its unique parent. If a node has fewer than two children, some of the child pointers may be set to a special null value, or to a special sentinel node. In languages with tagged unions such as ML, a tree node is often a tagged union of two types of nodes, one of which is a 3-tuple of data, left child, and right child, and the other of which is a "leaf" node, which contains no data and functions much like the null value in a language with pointers.

[edit] Arrays
Binary trees can also be stored in breadth-first order as an implicit data structure in arrays, and if the tree is a complete binary tree, this method wastes no space. In this compact arrangement, if a node has an index i, its children are found at indices (for the left child) and (for the right), while its parent (if any) is found at index (assuming the root has index zero). This method benefits from more compact storage and better locality of reference, particularly during a preorder traversal. However, it is expensive to grow and wastes space proportional to 2h - n for a tree of depth h with n nodes. This method of storage is often used for binary heaps. No space is wasted because nodes are added in breadth-first order.

[edit] Encodings
[edit] Succinct encodings
A succinct data structure is one which takes the absolute minimum possible space, as established by information theoretical lower bounds. The number of different binary trees on nodes is , the th Catalan number (assuming we view trees with identical structure as identical). For large , this is about ; thus we need at least about bits to encode it. A succinct binary tree therefore would occupy only 2 bits per node. One simple representation which meets this bound is to visit the nodes of the tree in preorder, outputting "1" for an internal node and "0" for a leaf. [1] If the tree contains data, we can simply simultaneously store it in a consecutive array in preorder. This function accomplishes this:
function EncodeSuccinct(node n, bitstring structure, array data) { if n = nil then append 0 to structure; else

append 1 to structure; append n.data to data; EncodeSuccinct(n.left, structure, data); EncodeSuccinct(n.right, structure, data); }

The string structure has only bits in the end, where is the number of (internal) nodes; we don't even have to store its length. To show that no information is lost, we can convert the output back to the original tree like this:
function DecodeSuccinct(bitstring structure, array data) { remove first bit of structure and put it in b if b = 1 then create a new node n remove first element of data and put it in n.data n.left = DecodeSuccinct(structure, data) n.right = DecodeSuccinct(structure, data) return n else return nil }

More sophisticated succinct representations allow not only compact storage of trees but even useful operations on those trees directly while they're still in their succinct form. The above program only works for a full binary tree.(i.e. each node is either a leaf or has at least 2 children).

[edit] Encoding general trees as binary trees


There is a one-to-one mapping between general ordered trees and binary trees, which in particular is used by Lisp to represent general ordered trees as binary trees. To convert a general ordered tree to binary tree, we only need to represent the general tree in left child-sibling way. The result of this representation will be automatically binary tree, if viewed from a different perspective. Each node N in the ordered tree corresponds to a node N' in the binary tree; the left child of N' is the node corresponding to the first child of N, and the right child of N' is the node corresponding to N 's next sibling --- that is, the next node in order among the children of the parent of N. This binary tree representation of a general order tree is sometimes also referred to as a left child-right sibling binary tree (LCRS tree), or a doubly chained tree, or a Filial-Heir chain. One way of thinking about this is that each node's children are in a linked list, chained together with their right fields, and the node only has a pointer to the beginning or head of this list, through its left field. For example, in the tree on the left, A has the 6 children {B,C,D,E,F,G}. It can be converted into the binary tree on the right.

The binary tree can be thought of as the original tree tilted sideways, with the black left edges representing first child and the blue right edges representing next sibling. The leaves of the tree on the left would be written in Lisp as:
(((N O) I J) C D ((P) (Q)) F (M))

which would be implemented in memory as the binary tree on the right, without any letters on those nodes that have a left child.

[edit] See also


2-3 tree 2-3-4 tree AA tree B-tree Binary space partitioning Elastic binary tree Huffman tree Kraft's inequality Random binary tree Recursion (computer science) Red-black tree Rope (computer science) Self-balancing binary search tree Strahler number Threaded binary Tree of primitive Pythagorean triples Alternative methods of generating the tree # Unrooted binary tree

[edit] Notes
1. ^ "perfect binary tree". NIST. http://www.nist.gov/dads/HTML/perfectBinaryTree.html.

2. ^ "complete binary tree". NIST. http://www.nist.gov/dads/HTML/completeBinaryTree.html. 3. ^ Aaron M. Tenenbaum, et. al Data Structures Using C, Prentice Hall, 1990 ISBN 0-13-199746-7 4. ^ Paul E. Black (ed.), entry for data structure in Dictionary of Algorithms and Data Structures. U.S. National Institute of Standards and Technology. 15 December 2004. Online version Accessed 2010-12-19. 5. ^ Mehta, Dinesh; Sartaj Sahni (2004). Handbook of Data Structures and Applications. Chapman and Hall. ISBN 1584884355. 6. ^ a b Dung X. Nguyen (2003). "Binary Tree Structure". rice.edu. http://www.clear.rice.edu/comp212/03-spring/lectures/22/. Retrieved December 28, 2010.

[edit] References

Donald Knuth. The art of computer programming vol 1. Fundamental Algorithms, Third Edition. Addison-Wesley, 1997. ISBN 0-201-89683-4. Section 2.3, especially subsections 2.3.12.3.2 (pp. 318348). Kenneth A Berman, Jerome L Paul. Algorithms: Parallel, Sequential and Distributed. Course Technology, 2005. ISBN 0-534-42057-5. Chapter 4. (pp. 113166).

[edit] External links


flash actionscript 3 opensource implementation of binary tree opensource library [2] GameDev.net's article about binary trees [3] Binary Tree Proof by Induction Balanced binary search tree on array How to create bottom-up an Ahnentafel list, or a balanced binary search tree on array [hide]

v t e

Trees in computer science


Binary trees

Binary search tree (BST) Cartesian tree Top tree T-tree AA tree AVL tree LLRB tree Redblack tree Scapegoat tree Splay tree

Selfbalancing binary search trees

Treap B+ tree B*-tree Bx-tree UB-tree 2-3 tree 2-3-4 tree (a,b)-tree Dancing tree Htree Suffix tree Radix tree Ternary search tree X-fast trie Y-fast trie Quadtree Octree k-d tree Implicit k-d tree vp-tree Exponential tree Fusion tree Interval tree PQ tree Range tree SPQR tree Van Emde Boas tree R-tree R+ tree R* tree X-tree M-tree Segment tree Hilbert R-tree Priority R-tree Heap Hash tree Finger tree Metric tree

B-trees

Tries

Binary space partitioning (BSP) trees

Non-binary trees

Spatial data partitioning trees

Other trees

Cover tree BK-tree Doubly-chained tree iDistance Link-cut tree Fenwick tree

Retrieved from "http://en.wikipedia.org/w/index.php?title=Binary_tree&oldid=484739303" View page ratings

Rate this page


What's this? Trustworthy

Objective

Complete

Well-written

I am highly knowledgeable about this topic (optional) Submit ratings Saved successfully Your ratings have not been submitted yet Categories:

Binary trees Data structures

Personal tools

Log in / create account

Namespaces

Article Talk

Variants Views Actions Search


Search Special:Search

Read Edit View history

Navigation

Main page Contents Featured content Current events Random article Donate to Wikipedia

Interaction Toolbox

Help About Wikipedia Community portal Recent changes Contact Wikipedia

What links here Related changes Upload file Special pages Permanent link Cite this page Rate this page

Print/export

Create a book Download as PDF Printable version

Languages

Catal esky Deutsch Espaol Esperanto Franais

Bahasa Indonesia slenska Italiano

Polski Portugus Romn Slovenina Slovenina / Srpski Suomi Svenska This page was last modified on 30 March 2012 at 19:10. Text is available under the Creative Commons Attribution-ShareAlike License; additional terms may apply. See Terms of use for details. Wikipedia is a registered trademark of the Wikimedia Foundation, Inc., a non-profit organization. Contact us Privacy policy About Wikipedia Disclaimers Mobile view

You might also like