Download CS2007Ch10B

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
COSC2007
Data Structures II
Chapter 11
Trees II
Topics

ADT Binary Tree (BT)



BT Implementation



2
Operations
Tree traversal
Array-based
LL-based
Expression Notation and Tree traversal
ADT Binary Tree
3
BT Traversal


Suppose I wanted to ‘visit’ all the nodes in this tree.
Furthermore, suppose I wanted to perform some
operation on the data there (such as printing it out).
root
A
B
C
D
H

4
E
I
J
F
K
G
L
What are some of the possible visitation
patterns we could use?
BT Traversal



Visit every node in a BT exactly once.
Each visit performs the same operations on each
node
Natural traversal orders:

Pre-order


In-order


Left-Node-Right (LNR)
Post-order

5
Node-Left-Right (NLR)
Left-Right-Node (LRN)
Pre-order Traversal


Each node is
processed the first
time it is observed.
i.e. before any node
in either subtree.


Visit Root Node
Visit Left subtree in
preorder
Visit Right subtree
Must be applied at all
6 levels of the tree.
A
1
B
2
C
9
D
3
A Possible Pattern


root
H
4

E
6
I
5
J
7
F
10
K
8
G
11
L
12
Called an PreOrder Traversal
Pre-order Traversal

Pseudocode
preorder (binaryTree:BinaryTree )
// Traverses the binary tree binaryTree in preorder.
// Assumes that “visit a node” means to display the node’s data item
if (binaryTree is not empty )
{
Display the data in the root of binaryTree
preorder ( Left subtree of binaryTree ’s root )
preorder ( Right subtree of binaryTree ’s root )
}
7
In-order Traversal


Each node is processed
the second time it is
observed. i.e. after all the
nodes in its left subtree
but before any of the
nodes in its right subtree.
A Possible Pattern




8
Visit Left subtree
Visit Root node
Visit Right subtree
Must be applied at all
levels of the tree.
root
A
8
B
4
C
10
D
2
H
1
E
6
I
3
J
5
F
9
K
7
G
11
L
12
In-order Traversal

Pseudocode
inorder (binaryTree:BinaryTree )
// Traverses the binary tree binaryTree in inorder.
// Assumes that “visit a node” means to display the node’s data item
if (binaryTree is not empty )
{
inorder ( Left subtree of binaryTree ’s root )
Display the data in the root of binaryTree
inorder ( Right subtree of binaryTree ’s root )
}
9
Post-order Traversal


Each node is
processed the third time
it is observed. i.e. after
all nodes in both of its
subtrees.
A Possible Pattern




10
Visit Left subtree
Visit Right subtree
Visit Root Node
Must be applied at all
levels of the tree.
root
A
12
B
7
C
11
D
3
H
1
E
6
I
2
J
4
F
8
G
10
K
5
HIDJKEBFLGCA
L
9
Post-order Traversal

Pseudocode
postorder (binaryTree:BinaryTree )
// Traverses the binary tree binaryTree in postorder.
// Assumes that “visit a node” means to display the node’s data item
if (binaryTree is not empty )
{
postorder ( Left subtree of binaryTree ’s root )
postorder ( Right subtree of binaryTree ’s root )
Display the data in the root of binaryTree
}
11
Implementation of BT

Possible Implementations:

Array based
Fast access
 Difficult to change
 Used if elements are not modified often


Reference (Pointer) based
Slower
 Easy to modify
 More flexible when elements are modified often

12
BT Array-Based Implementation

Nodes:


A Java Node class
Each node should contain:




Tony
Bob
Tree:


Array of structures
For empty tree

13
Data portion
Left-child index
Right-child index
James
index?
Adam
Davis
Neil
BT Array-Based Implementation
public class TreeNode
{
private Object item ;
private int leftChild;
private int rightChild;
// node in the tree
// data item in the tree
// index to left child
// index to right child
……. //constructor
} // end of TreeNode
public abstract class BinaryTreeArrayedBased {
14
protected final int MAX_NODES =100;
protected TreeNode tree [];
protected int root;
// index of root
protected int free; // index of next unused array location
……..//constructor and methods
} // end BinaryTreeArrayedBased
BT Array-Based Implementation
Array based is only good for complete tree
Since tree is complete, it maps nicely onto an array
A
representation.


C
B
D
H
T:
15
A
B
C
D
E
0
1
2
3
4
F
E
I
J
F
G
H
I
J
K
L
6
7
8
9
10
11 12
5
K
G
L
last
BT Array-Based Implementation
0
 For Complete Trees:
1
2
 A formula can be used to find the location of any
3
node in the tree
4
5
Lchild ( Tree [ i ] ) = Tree [ 2 * i + 1 ]
6
Rchild ( Tree [ i ] ) = Tree [ 2 * i + 2 ]
Parent (Tree [ i ] ) = Tree [ ( i - 1) / 2 ]
James
Tony
Bob
Adam
16
James
Bob
Tony
Adams
David
Neil
Davis
Neil
Reference-Based Implementation



17
Typical for implementing BTs
Only the pointer to the root of the tree can
be accessed by BT class clients
The data structure would be private data
member of a class of binary trees
Reference -Based Implementation
public class TreeNode
// node in the tree
{
private Object item;
// data portion
private TreeNode leftChildPtr; // pointer to left child
private TreeNode rightChildPtr;
// pointer to right child
TreeNode() {};
TreeNode(Object nodeItem, TreeNode left , TreeNode right )
{}
…….
} // end TreeNode class
18
Reference -Based Implementation
public abstract class BinaryTreeBasis
{
protected TreeNode root;
……. // constructor and methods
} // end BinaryTreeBasis class


If the tree is empty, then root is ?
The root of a nonempty BT has a left subtree and right
subtree, each is BT
root.getRight ()
 root.getLeft()

19
Reference -Based Implementation

Root
Example:
Item
LChildPtr
Root of left
child subtree
20
RChildPtr
Root of right
child subtree
The TreeNode Class
public class TreeNode {
private Object item;
private TreeNode leftChild;
private TreeNode rightChild;
public TreeNode() {} //Constructors
public TreeNode(Object myElement) {
item = myElement;
leftChild = null;
rightChild = null;
}
public TreeNode(Object newItem, TreeNode left, TreeNode right){
item = newItem;
21
leftChild = left;
rightChild = right;
}
TreeNode, cont'd.
public Object getItem()
{ return item;}
public void setItem(Object newItem)
{item = newItem;}
public void setLeft(TreeNode left)
{ leftChild = left;}
public TreeNode getLeft()
{ return leftChild;}
public void setRight(TreeNode right)
{ rightChild = right;}
public TreeNode getRight()
{ return rightChild;}
}
22
TreeException
public class TreeException extends RuntimeException
{
public TreeException(String s)
{
super (s);
}
} // end TreeException
23
The BinaryTreeBasis class
public abstract class BinaryTreeBasis {
protected TreeNode root;
public BinaryTreeBasis () {
root = null;
} //end constructor
public BinaryTreeBasis (object rootItem) {
root = new TreeNode (rootItem, null, null);
} //end constructor
public boolean isEmpty() {
//true is tree is empty
return root == null;
}
public void makeEmpty() { //sets root of tree to null
root =null;
24
}
The BinaryTreeBasis class
public Object getRootItem() throws TreeException {
if (root == null)
throw new TreeException (“ Empty tree”);
t:
else
return root.getItem();
} //end getRootItem()
public TreeNode getRoot() {
return root;
} //end getRoot()
} //end class BinaryTreeBasis
25
1
The BinaryTree Class
public class BinaryTree extends BinaryTreeBasis
{
//the Constructors
1
public BinaryTree() {}
t:
public BinaryTree(Object rootItem) {
super (rootItem);
} //end constructor
public BinaryTree(Object rootItem, BinaryTree leftTree, BinaryTree
rightTree) {
root = new TreeNode(rootItem, null, null);
attachLeftSubTree (leftTree);
attachRightSubTree (rightTree);
} // end constructor
••••••••all the methods go here
26
} //end BinaryTree
The BinaryTree Class
public void setRootItem(Object newItem) {
if (root == null)
root = new TreeNode (newItem, null,
null);
2
tree:
else
4
5
root.setItem(newItem);
} //end setRootItem
27
The BinaryTree Class
public void attachLeft(Object newItem) {
if (!isEmpty() && root.getLeft() == null)
root.setLeft(new TreeNode(newItem, null, null));
} // end attachLeft
t
1
2
public void attachRight(Object newItem) {
if (!isEmpty() && root.getRight() == null)
root.setRight(new TreeNode(newItem, null, null));
} // end attachRight
28
1
t:
3
2
t:
The BinaryTree Class
4
5
public void attachLeftSubtree(BinaryTree leftTree) throws TreeException
{
3
tree1:
if (isEmpty()) throw new TreeException("Cannot attach left
subtree to empty tree.");
6
else if (root.getLeft() != null) throw new
TreeException("Cannot overwrite left subtree.");
7
8
else { //no empty tree, no left child
root.setLeft(leftTree.root);
1
leftTree.makeEmpty();
t:
} //end attachLeftSubtree
2
}
4
3
5
6
7
29
8
The BinaryTree Class
public void attachRightSubtree(BinaryTree rightTree) throws
TreeException
{
if (isEmpty()) throw new TreeException("Cannot attach left
subtree to empty tree.");
else if (root.getRight() != null) throw new
TreeException("Cannot overwrite right subtree.");
else { //no empty tree, no right child
root.setRight(rightTree.root);
rightTree.makeEmpty();
} //end attachRightSubtree
}
30
The BinaryTree Class
protected BinaryTree (TreeNode rootNode) {
root = rootNode
} //end constructor
public BinaryTree detachLeftSubtree() throws TreeException
{
if (isEmpty()) throw new TreeException("Cannot detach empty tree.");
else { // create a tree points to the leftsubtree
BinaryTree leftTree;
leftTree = new BinaryTree (root.getLeft());
root.setLeft (null);
return leftTree;
}
} //end detachLeftSubtree
31
The BinaryTree Class
public BinaryTree detachRightSubtree() throws TreeException
{
if (isEmpty()) throw new TreeException("Cannot detach empty tree.");
else { // create a tree points to the rightsubtree
BinaryTree rightTree;
rightTree = new BinaryTree (root.getRight());
root.setRight (null);
return rightTree;
}
} //end detachRightSubtree
}
32
preOrderPrint( )
public void preOrderPrint(TreeNode rootNode)
throws TreeException
{
if (rootNode!=null)
{
System.out.print(rootNode.getItem() + " ");
preOrderPrint(rootNode.getLeft());
preOrderPrint(rootNode.getRight());
}
}
33
t:
1
2
4
3
5
6
7
8
Print tree using preorder traversal:
1 2 4 5 3 6 7 8
inOrderPrint()
public void inOrderPrint(TreeNode rootNode)
throws TreeException
{
if (rootNode!=null)
{
inOrderPrint(rootNode.getLeft());
System.out.print(rootNode.getItem() + " ");
inOrderPrint(rootNode.getRight());
}
}
34
t:
1
2
4
3
5
6
7
8
Print tree using inorder traversal:
4 2 5 1 7 6 8 3
postOrderPrint( )
public void postOrderPrint(TreeNode rootNode)
throws TreeException
{
if (rootNode!=null)
{
postOrderPrint(rootNode.getLeft());
postOrderPrint(rootNode.getRight());
System.out.print(rootNode.getItem() + " ");
}
}
35
t:
1
2
4
3
5
6
7
8
Print tree using postOrder traversal:
4 5 2 7 8 6 3 1
An Example Program
public class BinaryTreeTest
{
public static void main (String args[]) throws BinaryTreeException
{
1
t:
BinaryTree t = new BinaryTree(new Integer(1));
System.out.println("Element at root of tree = " + t.getRootElement());
System.out.println("Initial tree is: ");
t.preOrderPrint(t.getRoot());
System.out.println();
36
BinaryTree tree1 = new BinaryTree(new Integer(2));
tree1.attachLeft(new Integer(4));
tree1.attachRight(new Integer(5));
System.out.println("Tree1 is: ");
tree1.preOrderPrint(tree1.getRoot());
System.out.println();
tree1:
4
2
5
Example, cont'd.
BinaryTree tree2 = new BinaryTree(new Integer(6));
tree2.attachLeft(new Integer(7));
tree2.attachRight(new Integer(8));
System.out.println("tree2 is: ");
tree2.preOrderPrint(tree2.getRoot());
System.out.println();
BinaryTree tree3 = new BinaryTree(new Integer(3));
tree3.attachLeftSubtree(tree2);
System.out.println("Tree3 is: ");
tree3.preOrderPrint(tree3.getRoot());
System.out.println();
tree2:
t.attachLeftSubtree(tree1);
t.attachRightSubtree(tree3);
System.out.println("Final tree is: ");
t.preOrderPrint(t.getRoot());
System.out.println();
2
37
}
4
6
7
8
3
tree3:
6
7
t:
8
1
3
5
6
7
8
Expression Tree
Given a math expression, there exists a
unique corresponding expression tree.
5+ (6* (8-6))
+

5
*
6
8
38
6
Preorder Of Expression Tree
/
*
+
e
+
a
f
b
c
d
/ * +a b - c d +e f
Gives prefix form of expression!
39
Inorder Of Expression Tree
/
*
+
e
+
a
f
b
c
d
a + b * c - d/
e + f
Gives infix form of expression (sans parentheses)!
40
Postorder Of Expression Tree
/
*
+
e
+
a
f
b
c
d
a b +c d - * e f + /
Gives postfix form of expression!
41
Related documents