Binary Trees

Objectives:

Definitions and Properties

Definition. A binary tree is a finite set of nodes connected by edges such that:

Terminology:

 

 

Special binary trees

full binary tree: each node is either a leaf, or an internal node and has exactly two non-empty children

complete binary tree: all the levels are completely filled, excepting possibly the deepest one, which is filled from the left to the right

Characterization of binary trees

Theorem. The number of leaves in a non-empty full binary tree is one more than the number of internal nodes.

Proof. By mathematical induction on the number of internal nodes.

  1. Base:
  1. Induction hypothesis: assume that a full binary tree containing n-1 internal nodes has n leaves
  2. Induction step:

Theorem. The number of empty subtrees in a non-empty binary tree is one more than the number of nodes in the tree.

Proof.

Theorem. Any binary tree with n leaves has an average height of at least lgn.

Proof.

 

 

 

Binary tree traversals

Preorder traversal: visit the node first, then traverse its left subtree in preorder, then its right subtree in preorder

Postorder traversal: traverse the left subtree in postorder, then the right subtree in postorder, and finally visit the node itself

Inorder traversal: traverse the left subtree in inorder, then visit the node, and finally traverse the right subtree in inorder

 

The binary tree ADT

Type: a set of binary trees

Operations:

Binary tree implementations

  1. Pointer-based implementation

 

 

class BinNode{

public:

Element value;

BinNode* left;

BinNode* right;

BinNode(){left = right = NULL;}

BinNode(Element e,

BinNode* l=NULL,

BinNode* r=NULL){

value = e; left = l; right = r;

}

~BinNode() {};

};

 

Calculating the indicex of relatives of a node:

Binary search trees

Definition. A binary search tree (BST) is a binary tree in which all nodes of the left subtree of a node store values less than the value stored in that node, and all nodes of the right subtree of a node store values greater than the values stored in that node.

  1. deleting an arbitrary node

 

The major problem with the BST is that its shape depends on the order in which nodes are inserted.