Tree Data Tree Data StructuresStructures
Introductory ExamplesIntroductory Examples
WillliamWillliam
BillBill MaryMary
Curt MarjorieCurt Marjorie Richard AnneRichard AnneData organization such that items of information
are related by branches.
Branch Meaning: Parent Of
Introductory ExamplesIntroductory Examples
CurtCurt
BillBill Carol RonaldCarol Ronald
Alison Ashley William LauraAlison Ashley William Laura Victoria Victoria Jennifer ToddJennifer Todd
DylanDylan Trey ShelbyTrey Shelby
General Tree DefinitionGeneral Tree Definition
A tree is a finite set of one or more A tree is a finite set of one or more nodes such that:nodes such that: There is a specially designated node There is a specially designated node
called the called the rootroot The remaining nodes are partitioned The remaining nodes are partitioned
into n >= 0 into n >= 0 disjointdisjoint sets T1, T2, .. Tn, sets T1, T2, .. Tn, where each of these sets is a tree. T1, where each of these sets is a tree. T1, T2, … Tn are called T2, … Tn are called subtreessubtrees of the of the root.root.
Introductory ExamplesIntroductory Examples
CurtCurt
BillBill Carol RonaldCarol Ronald
Alison Ashley William LauraAlison Ashley William Laura Victoria Victoria Jennifer ToddJennifer Todd
DylanDylan Trey ShelbyTrey Shelby
Root: Curt
Bill is a subtree of Curt, and is a tree in itself
Introductory ExamplesIntroductory Examples
BillBill
Alison Alison Ashley Ashley
WilliamWilliam LauraLaura
DylanDylanRoot: Bill
Ashley is a subtree of Bill, and a tree in itself
Dylan is a subtree of Ashley, and a tree in itself
Tree DefinitionTree Definition Order of subtrees is irrelevantOrder of subtrees is irrelevant These two tree are equivalent:These two tree are equivalent:
CurtCurt BillBill Carol RonaldCarol Ronald
CurtCurtRonaldRonald Bill Bill CarolCarol
Tree DefinitionsTree Definitions A A nodenode is an item of information and has is an item of information and has
branches to other nodesbranches to other nodes Similar to linked list nodeSimilar to linked list node
The The degree degree of a node is the number of of a node is the number of subtrees of that nodesubtrees of that node
Nodes with a degree of 0 are terminal Nodes with a degree of 0 are terminal nodes or nodes or leaf leaf nodesnodes
Nodes with a degree > 0 are Nodes with a degree > 0 are non-non-terminalterminal nodes nodes
Tree DefinitionsTree Definitions
CurtCurt
BillBill Carol RonaldCarol Ronald
Alison Ashley William LauraAlison Ashley William Laura Victoria Jennifer Victoria Jennifer ToddTodd
DylanDylan Trey ShelbyTrey ShelbyDegree(Curt): 3 Degree(Bill): 4 Degree(Ashley): 1 Degree(William): 0
Terminal Nodes: Alison, Dylan, William, Laura, Trey, Shelby,
Jennifer, Todd, Ronald – Anyone with no children in real life
Tree DefinitionsTree Definitions
Roots of subtrees of nodes are Roots of subtrees of nodes are childrenchildren
ParentParent has one or more children has one or more children Children of the same parent are Children of the same parent are
siblingssiblings
Introductory ExamplesIntroductory Examples
CurtCurt
BillBill Carol RonaldCarol Ronald
Alison Ashley William LauraAlison Ashley William Laura Victoria Jennifer Victoria Jennifer ToddTodd
DylanDylan Trey ShelbyTrey Shelby
Children(Curt): Bill, Carol, Ronald
Parent(Jennifer): Carol Sibling(Ashley): Alison, William, Laura
Tree DefinitionsTree Definitions
GrandparentGrandparent is the parent of the is the parent of the parent of a nodeparent of a node
AncestorsAncestors: All nodes along the path : All nodes along the path from the root to the current node.from the root to the current node.
Descendants:Descendants: All elements in all All elements in all subtrees for which this node is a subtrees for which this node is a parent.parent.
Introductory ExamplesIntroductory Examples
CurtCurt
BillBill Carol RonaldCarol Ronald
Alison Ashley William LauraAlison Ashley William Laura Victoria Jennifer Victoria Jennifer ToddTodd
DylanDylan Trey ShelbyTrey Shelby
Grandparent(Dylan): Bill Ancestors(Dylan): Ashley, Bill, Curt
Descendants(Bill): Alison, Ashley, William, Laura, Dylan
Tree DefinitionsTree Definitions
Degree(Tree T):Degree(Tree T): Maximum degree Maximum degree of the nodes in T.of the nodes in T.
Level(Node N):Level(Node N): Level(Root): 1Level(Root): 1 Level(Non-Root): (Number of links Level(Non-Root): (Number of links
between root and the node) + 1between root and the node) + 1 Height(Tree T):Height(Tree T): Maximum level of Maximum level of
any node in T, also called any node in T, also called DepthDepth
Introductory ExamplesIntroductory Examples
CurtCurt
BillBill Carol RonaldCarol Ronald
Alison Ashley William LauraAlison Ashley William Laura Victoria Jennifer Victoria Jennifer ToddTodd
DylanDylan Trey ShelbyTrey Shelby
Degree(T): 4 [from Bill] Level(Curt): 1, Level(Ashley): 3, Level(Dylan): 4
Height(T): 4 [from Dylan]
Recursion and TreesRecursion and Trees
Note that the tree definition itself is Note that the tree definition itself is recursiverecursive Children of a node are roots of their Children of a node are roots of their
own treeown tree Most operators we define will be Most operators we define will be
recursive:recursive: Computing heightComputing height TraversingTraversing Searching for a nodeSearching for a node
Tree RepresentationsTree Representations Coding a Data Structure For Trees:Coding a Data Structure For Trees:
First thought: First thought: Follow our linked list node: Store data and Follow our linked list node: Store data and
pointers to the childrenpointers to the children
Sticky issues:Sticky issues: Need pointers to all childrenNeed pointers to all children What if variable number of children?What if variable number of children?
Tree RepresentationsTree Representations For a tree with fixed maximum degree of For a tree with fixed maximum degree of
k, could have each node store k pointers:k, could have each node store k pointers:
Potentially very wasteful: Assume k-ary Potentially very wasteful: Assume k-ary tree, with n nodestree, with n nodes nk – n + 1 unused pointersnk – n + 1 unused pointers Only use if most all pointers are going to be Only use if most all pointers are going to be
used – very dense treeused – very dense tree
DATA CHILD 1 CHILD 2 CHILD 3 CHILD 4
Node for tree with max degree 4
Tree RepresentationTree Representation Proof:Proof:
n nodes, each with k pointers : nk available n nodes, each with k pointers : nk available pointerspointers
Exactly one pointer to each valid node except Exactly one pointer to each valid node except root: root:
(n-1) used pointers(n-1) used pointers Total unused = nk – (n-1)Total unused = nk – (n-1) => nk – n + 1=> nk – n + 1
Example:Example: Turkett Family Tree: 4-ary, 14 nodesTurkett Family Tree: 4-ary, 14 nodes 56 – 14 + 1 = 43 unused pointers56 – 14 + 1 = 43 unused pointers
(172 bytes wasted)(172 bytes wasted) Mainly wasted in terminal nodesMainly wasted in terminal nodes
Tree RepresentationTree Representation
Representing arbitrary trees with Representing arbitrary trees with just two links per nodejust two links per node
Left-Child, Right-SiblingLeft-Child, Right-Sibling
Data
Left Child Right Sibling
Tree RepresentationTree Representation
Left Child, Right Sibling Family Tree Left Child, Right Sibling Family Tree
Curt
0
Bill Carol Ronald
0 0
Alison
0Victoria
Specialized TreesSpecialized Trees
Binary Tree:Binary Tree: A restriction of trees such that the maximum A restriction of trees such that the maximum
degree of a node is 2.degree of a node is 2. Order of nodes is now relevantOrder of nodes is now relevant May have zero nodesMay have zero nodes
Formal Definition:Formal Definition: A binary tree is a finite set of nodes that either A binary tree is a finite set of nodes that either
is empty or consists of a root and two disjoint is empty or consists of a root and two disjoint subtrees called the left subtree and the right subtrees called the left subtree and the right subtree.subtree.
Specialized TreesSpecialized Trees
These are equivalent trees, but are not equivalent binary trees, as binary trees enforce a more specific structure (a meaning of leftand right).
Types of Binary TreesTypes of Binary Trees
Skewed - UnbalancedComplete – More balanced,All terminals on same or adjacentlevels (Definition will come later)
Properties of Binary Properties of Binary TreesTrees
Given definition of binary tree, Given definition of binary tree, interesting (useful?) properties that interesting (useful?) properties that hold:hold:
Maximum number of nodes on level l is Maximum number of nodes on level l is 22l-1l-1
Maximum number of nodes in a binary Maximum number of nodes in a binary tree of depth k is 2tree of depth k is 2kk - 1 - 1
ProofsProofs
Maximum number of nodes on level l Maximum number of nodes on level l is 2is 2l-1l-1
Proof by induction:Proof by induction: Base step:Base step:
Level 1 = 2Level 1 = 21-1 1-1 = 2= 200 = 1, which holds (root) = 1, which holds (root) Assume holds for n, n > 1Assume holds for n, n > 1
Level n = 2Level n = 2n-1n-1
Each node in level n can have at most 2 Each node in level n can have at most 2 children in level n+1, so at most 2children in level n+1, so at most 2n-1n-1 * 2 = 2 * 2 = 2nn nodes in level n+1 => it holds (n+1-1 = n)nodes in level n+1 => it holds (n+1-1 = n)
ProofsProofs Maximum number of nodes in a binary Maximum number of nodes in a binary
tree of depth k is 2tree of depth k is 2kk – 1 – 1
Maximum number of nodes in tree is sum Maximum number of nodes in tree is sum over maximum nodes in a levelover maximum nodes in a level
Sum (l = 1 to k) (2Sum (l = 1 to k) (2l-1l-1) = ) = 1 + 2 + 4 + 8 …1 + 2 + 4 + 8 …Sum of all powers of 2 up to, but not Sum of all powers of 2 up to, but not
including, 2including, 2kk = 2 = 2kk -1 -1
Properties of Binary Properties of Binary TreesTrees
A A full binary treefull binary tree of depth k is a of depth k is a binary tree of depth k having 2binary tree of depth k having 2kk – 1 – 1 nodesnodes All nodes have two childrenAll nodes have two children All terminal nodes on same levelAll terminal nodes on same level
1
2 3
4 5 6 7
Properties of Binary Properties of Binary TreesTrees
A binary tree with n nodes and depth A binary tree with n nodes and depth k is k is completecomplete if its nodes correspond if its nodes correspond to the nodes numbered from 1 to n in to the nodes numbered from 1 to n in a full binary tree of depth ka full binary tree of depth k
The height of a complete binary tree The height of a complete binary tree with n nodes is (logwith n nodes is (log22(n+1)) – (n+1)) – Important and useful!Important and useful!
Properties of Binary Properties of Binary TreesTrees
Complete treesComplete trees 1
2 3
4 5 6 7
1
2 3
4 51
2 3
Binary Tree Binary Tree ImplementationImplementation
Array implementationArray implementation
Map each numbered node into Map each numbered node into appropriate spot in one-dimensional appropriate spot in one-dimensional arrayarray
1
2 3
4 5 6 7
Binary Tree Binary Tree ImplementationImplementation
Array implementation:Array implementation: If a complete binary tree with n nodes is If a complete binary tree with n nodes is
represented in an array:represented in an array: parent(i) is at floor ( i / 2) if i != 1 parent(i) is at floor ( i / 2) if i != 1
[i == 1 is the root which has no parent][i == 1 is the root which has no parent] left_child(i) = 2i. If 2i > n, i has no left left_child(i) = 2i. If 2i > n, i has no left
childchild right_child(i) = 2i + 1. If 2i + 1 > n, i has right_child(i) = 2i + 1. If 2i + 1 > n, i has
no right childno right child
Data1 Data2 Data3 Data4 Data5 Data6 Data7Blank
Array Index: 0 1 2 3 4 5 6 7
Binary Tree Binary Tree ImplementationImplementation
As before, array representations are not As before, array representations are not the best choice:the best choice: Fixed memory sizeFixed memory size
Doesn’t expand easilyDoesn’t expand easily Very wasteful of space unless well balanced.Very wasteful of space unless well balanced.
Better representation: Similar to linked list Better representation: Similar to linked list nodenode
Can move away from sibling representation Can move away from sibling representation and just point to two children from a nodeand just point to two children from a node
Binary Tree NodeBinary Tree Node
class BinaryTree; // forward declarationclass BinaryTree; // forward declarationclass BinaryTreeNodeclass BinaryTreeNode{{
friend class BinaryTree;friend class BinaryTree;private:private:
char data;char data;BinaryTreeNode* leftChild;BinaryTreeNode* leftChild;BinaryTreeNode* rightChild;BinaryTreeNode* rightChild;
};};
Binary Tree ClassBinary Tree Class
class BinaryTreeclass BinaryTree
{{public:public:
// public member methods// public member methods
private:private:
BinaryTreeNode* root;BinaryTreeNode* root;
};};
Binary Tree NodeBinary Tree Node
Only problem with linked node representation:Only problem with linked node representation: Difficult to find parentDifficult to find parent
OK:OK: Generally not that important to a lot of algorithmsGenerally not that important to a lot of algorithms If is important, when traversing list maintain a If is important, when traversing list maintain a
parent pointerparent pointer Could add a parent pointer link to all nodes if Could add a parent pointer link to all nodes if
particularly important without substantial changes, particularly important without substantial changes, but with n (number of nodes) bytes more use of but with n (number of nodes) bytes more use of memorymemory
QuestionsQuestions
For the binary tree below:For the binary tree below: What are terminal nodes? What are terminal nodes?
What are non-terminal What are non-terminal
nodes? nodes? What is level of each node? What is level of each node?
A
B
C D
E
D,E
A,B,C
A=1,B=2,CD=3,E=4
QuestionsQuestions
What is the maximum number of nodes What is the maximum number of nodes in a k-ary tree of height h?in a k-ary tree of height h? For 3 = 1 + 3 + 9 + 27 + 81 …For 3 = 1 + 3 + 9 + 27 + 81 … For 4 = 1 + 4 + 16 + 64 …For 4 = 1 + 4 + 16 + 64 … For k = 1 + k + kFor k = 1 + k + k22 + k + k33 … …
Sum of geometric series:Sum of geometric series: (k(khh-1) / (k-1)-1) / (k-1)k = 3, h = 4 = (3k = 3, h = 4 = (344 – 1) / (3-1) = 80/2 = – 1) / (3-1) = 80/2 = 4040Does it hold for 2? (2Does it hold for 2? (2hh-1) / (2-1) = 2-1) / (2-1) = 2hh-1-1
QuestionsQuestions
What would an array representation of What would an array representation of the following tree look like:the following tree look like:
A
B
C D
E
A B Blank C D Blank BlankBlank E Blank
Binary Tree ClassBinary Tree Class What are functions of interest?What are functions of interest?
class BinaryTreeclass BinaryTree
{{public:public:
BinaryTree(); // create empty treeBinaryTree(); // create empty treeBinaryTree(char data, BinaryTree bt1, BinaryTree bt2); BinaryTree(char data, BinaryTree bt1, BinaryTree bt2);
//construct a new tree , setting root data to data and links to //construct a new tree , setting root data to data and links to
//other trees//other trees
bool isEmpty(); // test whether emptybool isEmpty(); // test whether empty
BinaryTree leftChild(); // get left child of *thisBinaryTree leftChild(); // get left child of *this
BinaryTree rightChild(); // get right child of *thisBinaryTree rightChild(); // get right child of *this
char Data(); // return data in root node of *thischar Data(); // return data in root node of *this
};};
Binary Tree FunctionsBinary Tree Functions
Most operations performed on binary Most operations performed on binary trees require moving through the tree:trees require moving through the tree: Visiting nodesVisiting nodes Inserting an elementInserting an element Deleting an elementDeleting an element Non-recursive height calculationNon-recursive height calculation ……
Useful to have a simple mechanism for Useful to have a simple mechanism for moving through treesmoving through trees
Binary Tree TraversalBinary Tree Traversal
Tree traversal –Tree traversal – Visit each node in the tree exactly onceVisit each node in the tree exactly once Perform some operationPerform some operation
Print dataPrint data Add to sumAdd to sum Check for max heightCheck for max height
A traversal produces a linear ordering A traversal produces a linear ordering of the nodes [the order of visits]of the nodes [the order of visits]
Binary Tree TraversalBinary Tree Traversal
Treat trees and subtrees in same fashion Treat trees and subtrees in same fashion Traverse in same orderTraverse in same order Use recursion!Use recursion!
Let the following define traversal Let the following define traversal operations:operations: L => Move leftL => Move left V => Visit [Perform operation – print, sum, …]V => Visit [Perform operation – print, sum, …] R => Move rightR => Move right
Binary Tree TraversalBinary Tree Traversal
Six possible methods of traversal:Six possible methods of traversal: LVR, LRV, VLR, VRL, RVL, RLVLVR, LRV, VLR, VRL, RVL, RLV
Usually, only use three of these, all Usually, only use three of these, all with left before right:with left before right:LVRLVR LRVLRV VLRVLR
InorderInorder PostorderPostorder PreorderPreorder
Binary Tree TraversalBinary Tree Traversal
Let’s trace the traversal functions Let’s trace the traversal functions with examples of expressions with examples of expressions (operators and operand) (operators and operand)
Traversal Name corresponds to Traversal Name corresponds to order of outputted expressionorder of outputted expression
Binary Tree TraversalBinary Tree Traversal
+
* E
* D
/ C
A B
Inorder: LVR
A / B * C * D + E
Infix expression
Visit left child beforeparent
Binary Tree TraversalBinary Tree Traversal
Inorder implementation:Inorder implementation:
void BinaryTree::inorder()void BinaryTree::inorder(){{
inorder(root);inorder(root);}}
Void BinaryTree::inorder(BinaryTreeNode* node)Void BinaryTree::inorder(BinaryTreeNode* node){{
if (node)if (node){{
inorder(node->leftChild);inorder(node->leftChild);cout << node->data;cout << node->data; // replace cout with// replace cout with inorder(node->rightChild);inorder(node->rightChild); //arbitrary processing//arbitrary processing
}}}}
Binary Tree TraversalBinary Tree Traversal
+
* E
* D
/ C
A B
Postorder: LRV
A B / C * D * E +
Postfix expression
Visit left and right child before parent
Binary Tree TraversalBinary Tree Traversal
Postorder implementation:Postorder implementation:
void BinaryTree::postorder()void BinaryTree::postorder(){{
postorder(root);postorder(root);}}
void BinaryTree::postorder(BinaryTreeNode* node)void BinaryTree::postorder(BinaryTreeNode* node){{
if (node)if (node){{
postorder(node->leftChild);postorder(node->leftChild);postorder(node->rightChild);postorder(node->rightChild);cout << node->data;cout << node->data;
}}}}
Binary Tree TraversalBinary Tree Traversal
+
* E
* D
/ C
A B
Preorder: VLR
+ * * / A B C D E
Prefix expression
Visit parent before either child
Binary Tree TraversalBinary Tree Traversal
Preorder implementation:Preorder implementation:
void BinaryTree::preorder()void BinaryTree::preorder(){{
preorder(root);preorder(root);}}
Void BinaryTree::preorder(BinaryTreeNode* node)Void BinaryTree::preorder(BinaryTreeNode* node){{
if (node)if (node){{
cout << node->data;cout << node->data;preorder(node->leftChild);preorder(node->leftChild);preorder(node->rightChild);preorder(node->rightChild);
}}}}