- A nonlinear linked list in which each node may point to 0, 1, or two other nodes.
- Each node contains one or more data fields and two pointers.
- Tree pointer – Points to the first node in the binary tree.
- Root node – the node at the top of the tree.
- Leaf nodes – nodes that have no children.
- Child nodes, children – nodes below a given node
- Parent node – node above a given node.
- Subtree – portion of a tree from a node down to the leaves
Usage
- Binary search tree – data organized in a binary tree to simplify searches.
- Left subtree of a node contains data values < the data in the node.
- Right subtree of a node contains values > the data in the node.
Searching in a Binary Tree
- Start at root node
- Examine node data
- Is it the desired value?
- Else is desired data < node data? Repeat step 2 with left subtree
- Else is desired data > node data? Repeat step 2 with right subtree
- Continue until desired value found or NULL pointer reached.
Binary Search Tree Node
- A node in a binary tree is like a node in a linked list, with two node pointer fields
<li>struct TreeNode
{
int value;
TreeNode *left;
TreeNode *right;
}
Creating a New Node
- Allocate memory for new nodenewNode = new TreeNode;
- Initialize the contents of the nodenewNode – > value = num;
- Set the pointers to NULLnewNode – > Left= newNode – > Right
= NULL;
Inserting a Node
- If tree is empty, insert the new node as the root node.
- Else compare new node against left or right child, depending on whether data value of new node is < or > root node.
- Continue comparing and choosing left or right subtree until NULL pointer found.
- Set this NULL pointer to point to new node.
Traversing a Binary Tree
- Inorder
- Traverse left subtree of node
- Process data in node
- Traverse right subtree of node
- Preorder
- Process data in node
- Traverse left subtree of node
- Traverse right subtree of node
- Postorder
- Traverse left subtree of node
- Traverse right subtree of node
- Process data in node
Searching in a Binary Tree
- Start at root node, traverse the tree looking for value.
- Stop when value found or NULL pointer detected
- Can be implemented as a bool function
Deleting a Node from a Binary Tree – Leaf Node
- If node to be deleted is a leaf node, replace parent node’s pointer to it with a NULL pointer, then delete the node.
Deleting a Node from a Binary Tree – One Child
- If node to be deleted has one child node, adjust the pointers so that parent of node to be deleted points to child of node to be deleted, then delete the node.
Deleting a Node from a Binary Tree – Two Children
- If node to be deleted has left and right children,
- Promote one child to replace the deleted node
- Find the correct position for other child in subtree of promoted child