Objective: Understand Concepts related to trees. Introduction to Trees Computer Science 4 Reference: Objective: Understand Concepts related to trees.
What is a Binary Tree? Recall that in a linked list each node contains a link to another similar node. In a binary tree, each node contains a link to two other similar nodes. This leads to a linked data structure that “branches”.
A Binary tree B G O D W A T U
Some Terms Every binary tree has a node at the “top”. No other node references it. This is called the root node. Every binary tree has nodes where both references are null. I.e. it does not point to any lower nodes These are called leaf nodes.
Root Node B G O D W A T U
Leaf Nodes B G O D W A T U
Subtrees The references contained in a binary tree node are traditionally called the left and right childern. Each node can be said to have a left and right subtree Left subtree the left child and all its descendents. Right subtree includes the right child and all its descendants Note that a subtree (like any binary tree) may be empty.
Node B’s left subtree B G O D W A T U
Node B’s right subtree B G O D W A T U
Some More Terms The distance between a node and the root node is called its level Note that this makes the root node level 0 The maximum level in a tree is called its height. The maximum number of nodes on level L 1 for 0, 2 for 1, 4 for 2, 8 for 3, 16 for 4 In general 2L. The maximum number of nodes in a tree of height H 1 for 0, 3 for 1, 7 for 2, 15 for 3 In general, is 2H+1-1
This tree’s height is 3 Level B 1 G O D W A 2 T 3 U
Parent and Child Nodes When nodeA points to nodeB, we say NodeA is nodeB’s parent NodeB is nodeA’s child When nodeA is above nodeC in the tree, we say NodeA is an ancestor of NodeC NodeC is a descendant of NodeA
Node O is the parent of Node A B G O D W A T U
Node O is the child of Node B G O D W A T U
Node T is a descendant of node G B G O D W A T U
Node B is an ancestor of node W G O D W A T U
Minimum Height of a Binary Tree The maximum number of nodes in a binary tree of height H is 2H+1-1 Based on this, what’s the minimum number of levels of a tree containing N nodes. If N is 20 (1), need 0 levels. If N is 21 (2), need 1 level. If N is 22 (4), need 2 levels. If N is 23 (1), need 3 levels. If N is 2p, need P levels. Therefore need Floor(Log2N) levels to store N nodes.
Summary Each node in a binary contains references to two other nodes. Root node at the top of the tree Leaf nodes don’t reference any other nodes Height of the tree is the number of levels Parents and children, ancestors and descendants. Can store 2L nodes on level L Minimum height of a tree with N items is Log2N