| • Science | • People | • Locations | • Timeline |
In computer science, a binary tree is an ordered tree data structure in which each node has at most two children. Typically the child nodes are called left and right. One common use of binary trees is binary search trees; another is binary heaps.
A binary tree is a rooted tree in which every node has at most two children.
A full binary tree is a tree which every node has zero or two children.
A perfect binary tree is a complete binary tree in which leaves (vertices with zero children) are at the same depth (distance from the root, also called height).
Sometimes the perfect binary tree is called the complete binary tree. Some others define a complete binary tree to be a full binary tree in which all leaves are at depth n or n-1 for some n.
Binary trees can be constructed from programming language primitives in several ways. 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.
Binary trees can also be stored 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 2i+1 and 2i+2, while its parent (if any) is found at index floor((i-1)/2) (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 requires contiguous memory, is expensive to grow, and wastes space proportional to 2h - n for a tree of height h with n nodes.
In languages with tagged unions such as MLML is a general-purpose functional programming language developed by Robin Milner and others in the late 1970s at Edinburgh University, whose syntax is inspired by ISWIM. Historically, ML stands for metalanguage as it was conceived to develop proof tactic, 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.
Often, one wishes to visit each of the nodes in a tree and examine the value there. 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.