Binary Tree 1
Binary Tree 1
Outline
• Binary Trees and Binary Search Trees
• Implementing Binary Trees
• Insertion and Deletion in Binary Search Trees
• Tree Traversal
Definitions
• A tree is a data type that
consists of nodes and arcs
• These trees are depicted
upside down with the root at
the top and the leaves
(terminal nodes) at the
bottom
• The root is a node that has no
parent
• Leaves have no children
Definitions
• Each node must be reachable from the root through a
unique sequence of arcs, called a path
• The number of arcs in a path is called the length of the
path
• The level of a node is the length of the path from the
root to the node plus 1, which is the number of nodes in
the path
• The height of a nonempty tree is the maximum level of a
node in the tree
Binary Trees
• A binary tree is a tree whose nodes have two children
(possibly empty), and each child is designated as either
a left child or a right child
Binary Trees
• A complete binary tree is tree where all nonterminal
nodes have both their children, and all leaves are at the
same level
• A decision tree is a binary tree in which all nodes have
either zero or two nonempty children
Binary Search Tree
• binary search tree (BST) or ordered binary tree is
binary tree with the following properties;
– for each node n of the tree, all values stored in its left subtree
are less than value v stored in n
– all values stored in the right subtree are greater than v.
Implementing Binary Trees
• Binary trees can be implemented in at least two ways:
– As arrays
– As linked structures
• To implement a tree as an array, a node is declared as
an object with an information field and two “reference”
fields that points to the left and right child nodes
Implementing Binary Trees
Deleting a leaf
The height of a tree can be (a) extended or (b) reduced after deleting by merging.
Deletion by Copying
• If the node has two children, the problem can be reduced
to:
– The node is a leaf
– The node has only one nonempty child
• Solution: replace the key being deleted with its
immediate predecessor (or successor)
• A key’s predecessor is the key in the rightmost node in
the left subtree
Deletion by Copying
Deletion by copying
Tree Traversal
• Tree traversal is the process of visiting each node in the
tree exactly one time
• Breadth-First traversal is visiting each node starting
from the lowest (or highest) level and moving down (or
up) level by level, visiting nodes on each level from left to
right (or from right to left)
Breadth-First Traversal