Movatterモバイル変換


[0]ホーム

URL:


Jump to content
WikipediaThe Free Encyclopedia
Search

Binary tree

From Wikipedia, the free encyclopedia
Limited form of tree data structure
Not to be confused withBinary search tree,B-tree, orB+ tree.
A labeled binary tree of size 9 and height 3, with a root node whose value is 1. The above tree is unbalanced and not sorted.
A labeled binary tree of size 9 (the number of nodes in the tree) and height 3 (the height of a tree defined as the number of edges or links from the top-most or root node to the farthest leaf node), with a root node whose value is 1. The above tree is unbalanced and not sorted.

Incomputer science, abinary tree is atree data structure in which each node has at most twochildren, referred to as theleft child and theright child. That is, it is ak-ary tree withk = 2. Arecursive definition usingset theory is that a binary tree is atuple (L,S,R), whereL andR are binary trees or theempty set andS is asingleton set containing the root.[1][2]

From agraph theory perspective, binary trees as defined here arearborescences.[3] A binary tree may thus be also called abifurcating arborescence,[3] a term which appears in some early programming books[4] before the modern computer science terminology prevailed. It is also possible to interpret a binary tree as anundirected, rather thandirected graph, in which case a binary tree is anordered,rooted tree.[5] Some authors userooted binary tree instead ofbinary tree to emphasize the fact that the tree is rooted, but as defined above, a binary tree is always rooted.[6]

In mathematics, what is termedbinary tree can vary significantly from author to author. Some use the definition commonly used in computer science,[7] but others define it as every non-leaf having exactly two children and don't necessarily label the children as left and right either.[8]

In computing, binary trees can be used in two very different ways:

  • First, as a means of accessing nodes based on some value or label associated with each node.[9] Binary trees labelled this way are used to implementbinary search trees andbinary heaps, and are used for efficientsearching andsorting. The designation of non-root nodes as left or right child even when there is only one child present matters in some of these applications, in particular, it is significant in binary search trees.[10] However, the arrangement of particular nodes into the tree is not part of the conceptual information. For example, in a normal binary search tree the placement of nodes depends almost entirely on the order in which they were added, and can be re-arranged (for example bybalancing) without changing the meaning.
  • Second, as a representation of data with a relevant bifurcating structure. In such cases, the particular arrangement of nodes under and/or to the left or right of other nodes is part of the information (that is, changing it would change the meaning). Common examples occur withHuffman coding andcladograms. The everyday division of documents into chapters, sections, paragraphs, and so on is an analogous example withn-ary rather than binary trees.

Definitions

[edit]

Recursive definition

[edit]
This articlemay need to be rewritten to comply with Wikipedia'squality standards, as section.You can help. Thetalk page may contain suggestions.(July 2014)

To define a binary tree, the possibility that only one of the children may be empty must be acknowledged. Anartifact, which in some textbooks is called anextended binary tree, is needed for that purpose. An extended binary tree is thus recursively defined as:[11]

  • theempty set is an extended binary tree
  • if T1 and T2 are extended binary trees, then denote by T1 • T2 the extended binary tree obtained byadding a rootr connected to the left to T1 and to the right to T2[clarification needed where did the 'r' go in the 'T1 • T2' symbol] by adding edges when these sub-trees are non-empty.

Another way of imagining this construction (and understanding the terminology) is to consider instead of the empty set a different type of node—for instance square nodes if the regular ones are circles.[12]

Using graph theory concepts

[edit]

A binary tree is arooted tree that is also anordered tree (a.k.a. plane tree) in which every node has at most two children. A rooted tree naturally imparts a notion of levels (distance from the root); thus, for every node, a notion of children may be defined as the nodes connected to it a level below. Ordering of these children (e.g., by drawing them on a plane) makes it possible to distinguish a left child from a right child.[13] But this still does not distinguish between a node with left but not a right child from a node with right but no left child.

The necessary distinction can be made by first partitioning the edges; i.e., defining the binary tree as triplet (V, E1, E2), where (V, E1 ∪ E2) is a rooted tree (equivalently arborescence) and E1 ∩ E2 is empty, and also requiring that for allj ∈ { 1, 2 }, every node has at most one Ej child.[14] A more informal way of making the distinction is to say, quoting theEncyclopedia of Mathematics, that "every node has a left child, a right child, neither, or both" and to specify that these "are all different" binary trees.[7]

Types of binary trees

[edit]

Tree terminology is not well-standardized and therefore may vary among examples in the available literature.

  • Arooted binarytree has aroot node and every node has at most two children.
A full binary tree
Anancestry chart which can be mapped to a perfect 4-level binary tree.
  • Afull binary tree (sometimes referred to as aproper,[15]plane, orstrict binary tree)[16][17] is a tree in which every node has either 0 or 2 children. Another way of defining a full binary tree is arecursive definition. A full binary tree is either:[11]
    • A single vertex (a single node as the root node).
    • A tree whose root node has two subtrees, both of which are full binary trees.
  • Aperfect binary tree is a binary tree in which all interior nodes have two childrenand all leaves have the samedepth or samelevel (the level of a node defined as the number of edges or links from the root node to a node).[18] A perfect binary tree is a full binary tree.
  • Acomplete binary tree is a binary tree in which every level,except possibly the last, is completely filled, and all nodes in the last level are as far left as possible. It can have between 1 and 2h nodes at the last levelh.[19] A perfect tree is therefore always complete but a complete tree is not always perfect. Some authors use the termcomplete to refer instead to aperfect binary tree as defined above, in which case they call this type of tree (with a possibly not filled last level) analmost complete binary tree ornearly complete binary tree.[20][21] A complete binary tree can be efficiently represented using an array.[19]
A complete binary tree (that is not full)
  • Theinfinite complete binary tree is a tree with0{\displaystyle {\aleph _{0}}} levels, where for each leveld the number of existing nodes at level d is equal to 2d. The cardinal number of the set of all levels is0{\displaystyle {\aleph _{0}}} (countably infinite). The cardinal number of the set of all paths (the "leaves", so to speak) is uncountable, having thecardinality of the continuum.
  • Abalanced binary tree is a binary tree structure in which the left and right subtrees of every node differ in height (the number of edges from the top-most node to the farthest node in a subtree) by no more than 1 (or the skew is no greater than 1).[22] One may also consider binary trees where no leaf is much farther away from the root than any other leaf. (Different balancing schemes allow different definitions of "much farther".[23])
  • Adegenerate (orpathological) tree is where each parent node has only one associated child node.[24] This means that the tree will behave like alinked list data structure. In this case, an advantage of using a binary tree is significantly reduced because it is essentially a linked list whichtime complexity is O(n) (n as the number of nodes) and it has more data space than the linked list due to two pointers per node, while the complexity of O(log2n) for data search in a balanced binary tree is normally expected.

Properties of binary trees

[edit]

Combinatorics

[edit]
This sectiondoes notcite anysources. Please helpimprove this section byadding citations to reliable sources. Unsourced material may be challenged andremoved.(July 2014) (Learn how and when to remove this message)

Incombinatorics, 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 numbern of internal nodes (those with two children); the other nodes are leaf nodes and there aren + 1 of them. The number of such binary trees of sizen is equal to the number of ways of fully parenthesizing a string ofn + 1 symbols (representing leaves) separated byn binary operators (representing internal nodes), to determine the argument subexpressions of each operator. For instance forn = 3 one has to parenthesize a string likeXXXX{\displaystyle X*X*X*X}, which is possible in five ways:

((XX)X)X,(X(XX))X,(XX)(XX),X((XX)X),X(X(XX)).{\displaystyle ((X*X)*X)*X,\qquad (X*(X*X))*X,\qquad (X*X)*(X*X),\qquad X*((X*X)*X),\qquad X*(X*(X*X)).}

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 sizesi andj respectively, the full tree has sizei +j + 1. Therefore, the numberCn{\displaystyle C_{n}} of binary trees of sizen has the following recursive descriptionC0=1{\displaystyle C_{0}=1}, andCn=i=0n1CiCn1i{\displaystyle \textstyle C_{n}=\sum _{i=0}^{n-1}C_{i}C_{n-1-i}} for any positive integern. It follows thatCn{\displaystyle C_{n}} is theCatalan number of indexn.

The above parenthesized strings should not be confused with the set of words of length 2n in theDyck 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 satisfyi +j + 1 =n); this number is therefore also the Catalan numberCn{\displaystyle C_{n}}. So there are also five Dyck words of length 6:

()()(),     ()(()),     (())(),     (()()),     ((()))

These Dyck words do not correspond to binary trees in the same way. Instead, they are related by the following recursively defined bijection: the Dyck word equal to the empty string corresponds to the binary tree of size 0 with only one leaf. Any other Dyck word can be written as (w1{\displaystyle w_{1}})w2{\displaystyle w_{2}}, wherew1{\displaystyle w_{1}},w2{\displaystyle w_{2}} are themselves (possibly empty) Dyck words and where the two written parentheses are matched. The bijection is then defined by letting the wordsw1{\displaystyle w_{1}} andw2{\displaystyle w_{2}} correspond to the binary trees that are the left and right children of the root.

A bijective correspondence can also be defined as follows: enclose the Dyck word in an extra pair of parentheses, so that the result can be interpreted as aLisp list expression (with the empty list () as only occurring atom); then thedotted-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 afree magma on a singleton set.

Methods for storing binary trees

[edit]

Binary trees can be constructed fromprogramming language primitives in several ways.

Nodes and references

[edit]

In a language withrecords andreferences, 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 specialsentinel node.

This method of storing binary trees wastes a fair bit of memory, as the pointers will be null (or point to the sentinel) more than half the time; a more conservative representation alternative isthreaded binary tree.[26]

In languages withtagged unions such asML, 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. For example, the following line of code inOCaml (an ML dialect) defines a binary tree that stores a character in each node.[27]

typechr_tree=Empty|Nodeofchar*chr_tree*chr_tree

Arrays

[edit]

Binary trees can also be stored in breadth-first order as animplicit data structure inarrays, and if the tree is a complete binary tree, this method wastes no space. In this compact arrangement, if a node has an indexi, its children are found at indices2i+1{\displaystyle 2i+1} (for the left child) and2i+2{\displaystyle 2i+2} (for the right), while its parent (if any) is found at indexi12{\displaystyle \left\lfloor {\frac {i-1}{2}}\right\rfloor } (assuming the root has index zero). Alternatively, with a 1-indexed array, the implementation is simplified with children found at2i{\displaystyle 2i} and2i+1{\displaystyle 2i+1}, and parent found ati/2{\displaystyle \lfloor i/2\rfloor }.[28]

This method benefits from more compact storage and betterlocality of reference, particularly during a preorder traversal. It is often used forbinary heaps.[29]

A small complete binary tree stored in an array
A small complete binary tree stored in an array

Encodings

[edit]

Succinct encodings

[edit]

Asuccinct data structure is one which occupies close to minimum possible space, as established byinformation theoretical lower bounds. The number of different binary trees onn{\displaystyle n} nodes isCn{\displaystyle \mathrm {C} _{n}}, then{\displaystyle n}thCatalan number (assuming we view trees with identicalstructure as identical). For largen{\displaystyle n}, this is about4n{\displaystyle 4^{n}}; thus we need at least aboutlog24n=2n{\displaystyle \log _{2}4^{n}=2n} bits to encode it. A succinct binary tree therefore would occupy2n+o(n){\displaystyle 2n+o(n)} bits.

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.[30] 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 =nilthen        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 stringstructure has only2n+1{\displaystyle 2n+1} bits in the end, wheren{\displaystyle n} 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 ofstructure and put it inbif b = 1then        create a new noden        remove first element of data and put it in n.data        n.left = DecodeSuccinct(structure, data)        n.right = DecodeSuccinct(structure, data)return nelsereturn 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.

Encoding ordered trees as binary trees

[edit]

There is a natural one-to-one correspondence between ordered trees and binary trees. It allows any ordered tree to be uniquely represented as a binary tree, and vice versa:

LetT be a node of an ordered tree, and letB denoteT's image in the corresponding binary tree. ThenB'sleft child representsT's first child, while theB's right child representsT's next sibling.

For example, the ordered tree on the left and the binary tree on the right correspond:

An example of converting an n-ary tree to a binary tree
An example of converting an n-ary tree to a binary tree

In the pictured binary tree, the black, left, edges representfirst child, while the blue, right, edges representnext sibling.

This representation is called aleft-child right-sibling binary tree.

Common operations

[edit]
Tree rotations are very common internal operations onself-balancing binary trees.

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

Insertion

[edit]

Nodes can be inserted into binary trees in between two other nodes or added after aleaf node. In binary trees, a node that is inserted is specified as to whose child it will be.

Leaf nodes

[edit]

To add a new node after leaf node A, A assigns the new node as one of its children and the new node assigns node A as its parent.

Internal nodes

[edit]
The process of inserting a node into a binary tree

Insertion oninternal nodes is slightly more complex than on leaf 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.

Deletion

[edit]

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

Node with zero or one children

[edit]
The process of deleting an internal node in a binary tree

Suppose that the node to delete is node A. If A has no children, deletion is accomplished by setting the child of A's parent tonull. If A 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.

Node with two children

[edit]

In a binary tree, a node with two children cannot be deleted unambiguously.[31] However, in certain binary trees (includingbinary search trees) these nodescan be deleted, though with a rearrangement of the tree structure.

Traversal

[edit]
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. Below are the brief descriptions of above mentioned traversals.

Pre-order

[edit]

In pre-order, we always visit the current node; next, we recursively traverse the current node's left subtree, and then we recursively traverse the current node's right subtree. The pre-order traversal is atopologically sorted one, because a parent node is processed before any of its child nodes is done.

In-order

[edit]

In in-order, we always recursively traverse the current node's left subtree; next, we visit the current node, and lastly, we recursively traverse the current node's right subtree.

Post-order

[edit]

In post-order, we always recursively traverse the current node's left subtree; next, we recursively traverse the current node's right subtree and then visit the current node. Post-order traversal can be useful to get postfix expression of abinary expression tree.[32]

Depth-first order

[edit]

In depth-first order, we always attempt to visit the node farthest from the root node 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. Seedepth-first search for more information.

Breadth-first order

[edit]

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. Seebreadth-first search for more information. Also called alevel-order traversal.

In a complete binary tree, a node's breadth-index (i − (2d − 1)) can be used as traversal instructions from the root. Reading bitwise from left to right, starting at bitd − 1, whered is the node's distance from the root (d = ⌊log2(i+1)⌋) and the node in question is not the root itself (d > 0). When the breadth-index is masked at bitd − 1, the bit values0 and1 mean to step either left or right, respectively. The process continues by successively checking the next bit to the right until there are no more. The rightmost bit indicates the final traversal from the desired node's parent to the node itself. There is a time-space trade-off between iterating a complete binary tree this way versus each node having pointer(s) to its sibling(s).

See also

[edit]

References

[edit]

Citations

[edit]
  1. ^Rowan Garnier; John Taylor (2009).Discrete Mathematics:Proofs, Structures and Applications, Third Edition. CRC Press. p. 620.ISBN 978-1-4398-1280-8.
  2. ^Steven S Skiena (2009).The Algorithm Design Manual. Springer Science & Business Media. p. 77.ISBN 978-1-84800-070-4.
  3. ^abKnuth (1997).The Art Of Computer Programming, Volume 1, 3/E. Pearson Education. p. 363.ISBN 0-201-89683-4.
  4. ^Iván Flores (1971).Computer programming system/360. Prentice-Hall. p. 39.
  5. ^Kenneth Rosen (2011).Discrete Mathematics and Its Applications, 7th edition. McGraw-Hill Science. p. 749.ISBN 978-0-07-338309-5.
  6. ^David R. Mazur (2010).Combinatorics: A Guided Tour. Mathematical Association of America. p. 246.ISBN 978-0-88385-762-5.
  7. ^ab"Binary tree",Encyclopedia of Mathematics,EMS Press, 2001 [1994] also in print asMichiel Hazewinkel (1997).Encyclopaedia of Mathematics. Supplement I. Springer Science & Business Media. p. 124.ISBN 978-0-7923-4709-5.
  8. ^L.R. Foulds (1992).Graph Theory Applications. Springer Science & Business Media. p. 32.ISBN 978-0-387-97599-3.
  9. ^David Makinson (2009).Sets, Logic and Maths for Computing. Springer Science & Business Media. p. 199.ISBN 978-1-84628-845-6.
  10. ^Jonathan L. Gross (2007).Combinatorial Methods with Computer Applications. CRC Press. p. 248.ISBN 978-1-58488-743-0.
  11. ^abKenneth Rosen (2011).Discrete Mathematics and Its Applications 7th edition. McGraw-Hill Science. pp. 352–353.ISBN 978-0-07-338309-5.
  12. ^Te Chiang Hu; Man-tak Shing (2002).Combinatorial Algorithms. Courier Dover Publications. p. 162.ISBN 978-0-486-41962-6.
  13. ^Lih-Hsing Hsu; Cheng-Kuan Lin (2008).Graph Theory and Interconnection Networks. CRC Press. p. 66.ISBN 978-1-4200-4482-9.
  14. ^J. Flum;M. Grohe (2006).Parameterized Complexity Theory. Springer. p. 245.ISBN 978-3-540-29953-0.
  15. ^Tamassia, Michael T. Goodrich, Roberto (2011).Algorithm design : foundations, analysis, and Internet examples (2 ed.). New Delhi: Wiley-India. p. 76.ISBN 978-81-265-0986-7.{{cite book}}: CS1 maint: multiple names: authors list (link)
  16. ^"full binary tree".NIST.
  17. ^Richard Stanley, Enumerative Combinatorics, volume 2, p.36
  18. ^"perfect binary tree".NIST.
  19. ^ab"complete binary tree". NIST.
  20. ^"almost complete binary tree". Archived fromthe original on 2016-03-04. Retrieved2015-12-11.
  21. ^"nearly complete binary tree"(PDF).Archived(PDF) from the original on 2022-10-09.
  22. ^Aaron M. Tenenbaum, et al. Data Structures Using C, Prentice Hall, 1990ISBN 0-13-199746-7
  23. ^Paul E. Black (ed.), entry fordata structure inDictionary of Algorithms and Data Structures. U.S.National Institute of Standards and Technology. 15 December 2004.Online versionArchived December 21, 2010, at theWayback Machine Accessed 2010-12-19.
  24. ^Parmar, Anand K. (2020-01-22)."Different Types of Binary Tree with colourful illustrations".Medium. Retrieved2020-01-24.
  25. ^Mehta, Dinesh;Sartaj Sahni (2004).Handbook of Data Structures and Applications.Chapman and Hall.ISBN 1-58488-435-5.
  26. ^D. Samanta (2004).Classic Data Structures. PHI Learning Pvt. Ltd. pp. 264–265.ISBN 978-81-203-1874-8.
  27. ^Michael L. Scott (2009).Programming Language Pragmatics (3rd ed.). Morgan Kaufmann. p. 347.ISBN 978-0-08-092299-7.
  28. ^Introduction to algorithms. Cormen, Thomas H., Cormen, Thomas H. (2nd ed.). Cambridge, Mass.: MIT Press. 2001. p. 128.ISBN 0-262-03293-7.OCLC 46792720.{{cite book}}: CS1 maint: others (link)
  29. ^Laakso, Mikko."Priority Queue and Binary Heap".University of Aalto. Retrieved2023-10-11.
  30. ^Demaine, Erik."6.897: Advanced Data Structures Spring 2003 Lecture 12"(PDF). MIT CSAIL. Archived fromthe original(PDF) on 24 November 2005. Retrieved14 April 2022.
  31. ^abDung X. Nguyen (2003)."Binary Tree Structure". rice.edu. RetrievedDecember 28, 2010.
  32. ^Wittman, Todd (2015-02-13)."Lecture 18: Tree Traversals"(PDF). Archived fromthe original(PDF) on 2015-02-13. Retrieved2023-04-29.

Bibliography

[edit]

External links

[edit]
Wikimedia Commons has media related toBinary trees.
Search trees
(dynamic sets/associative arrays)
Heaps
Tries
Spatial data partitioning trees
Other trees
Authority control databases: NationalEdit this at Wikidata
Retrieved from "https://en.wikipedia.org/w/index.php?title=Binary_tree&oldid=1281586182"
Category:
Hidden categories:

[8]ページ先頭

©2009-2025 Movatter.jp