Académique Documents
Professionnel Documents
Culture Documents
Binary Trees
Chapter Objectives
Learn about binary trees Explore various binary tree traversal algorithms Learn how to organize data in a binary search tree Discover how to insert and delete items in a binary search tree Explore nonrecursive binary tree traversal algorithms Learn about AVL (height-balanced) trees
Data Structures Using Java 2
Binary Trees
Definition: A binary tree, T, is either empty or such that:
T has a special node called the root node; T has two sets of nodes, LT and RT, called the left subtree and right subtree of T, respectively; LT and RT are binary trees
Binary Tree
LA = empty
RA = empty
Binary Trees
Following class defines the node of a binary tree:
protected class BinaryTreeNode { DataElement info; BinaryTreeNode llink; BinaryTreeNode rlink; }
Nodes
For each node:
Data is stored in info The reference to the left child is stored in llink The reference to the right child is stored in rlink
10
11
12
13
14
Copy Tree
Useful operation on binary trees is to make identical copy of binary tree Method copy useful in implementing copy constructor and method copyTree
15
Method copy
BinaryTreeNode copy(BinaryTreeNode otherTreeRoot) { BinaryTreeNode temp; if(otherTreeRoot == null) temp = null; else { temp = new BinaryTreeNode(); temp.info = otherTreeRoot.info.getCopy(); temp.llink = copy(otherTreeRoot.llink); temp.rlink = copy(otherTreeRoot.rlink); } return temp; }//end copy
16
Method copyTree
public void copyTree(BinaryTree otherTree) { if(this != otherTree) //avoid self-copy { root = null; if(otherTree.root != null) //otherTree is //nonempty root = copy(otherTree.root); } }
17
Traversals
Inorder
Traverse the left subtree Visit the node Traverse the right subtree
Preorder
Visit the node Traverse the left subtree Traverse the right subtree
19
Traversals
Postorder
Traverse the left subtree Traverse the right subtree Visit the node
20
21
22
23
24
25
27
28
29
30
31
32
33
34
35
current = root; //start traversal at root node v = 0; if(current is NULL) the binary tree is empty if(current is not NULL) a. push current into stack; b. push 1 onto stack; c. current = current.llink; d. while(stack is not empty) if(current is not NULL and v is 0)
{
37
38
39
40
AVL Trees
41
Non-AVL Trees
42
43
44
45
46
47
Left rotation: certain nodes from the right subtree of x move to its left subtree; the root of the right subtree of x becomes the new root of the reconstructed subtree Right rotation at x: certain nodes from the left subtree of x move to its right subtree; the root of the left subtree of x becomes the new root of the reconstructed subtree
Data Structures Using Java 48
49
50
51
52
53
54
55
56
57
59
Chapter Summary
Binary trees Binary search trees Recursive traversal algorithms Nonrecursive traversal algorithms AVL trees
60