Practical 5 - Tree Implementation
Practical 5 - Tree Implementation
Tree Implementation
public class Node {
public int iData;
public double dData;
public Node leftChild; // left nod
public Node rightChild; // right node
Tree Class
class Tree {
public Node root;
public Tree() {
root = null;
}
1
newnode.iData = id;
if (root == null) {
root = newnode;
} else {
Node current = root;
Node parent;
while (true) {
parent = current;
if (id < current.iData) {
current = current.leftChild;
if (current == null) {
parent.leftChild = newnode;
return;
}
} else {
current = current.rightChild;
if (current == null) {
parent.leftChild = newnode;
return;
}
}
}
}
}
2
} else if (current.rightChild == null)
if (current == root)
root = current.leftChild;
else if (isLeftChild)
parent.leftChild = current.leftChild;
else
parent.rightChild = current.leftChild;
else if (current.leftChild == null)
if (current == root)
root = current.rightChild;
else if (isLeftChild)
parent.leftChild = current.rightChild;
else
parent.rightChild = current.leftChild;
else {
Node successor = getSuccessor(current);
if (current == root)
root = successor;
else if (isLeftChild)
parent.leftChild = successor;
successor.leftChild = current.leftChild;
}
return true;
}
3
System.out.println("\n Inorder traversal");
inorder(root);
break;
case 3:
System.out.println("\n postorder traversal");
postorder(root);
break;
}
System.out.println();
}
4
TreeTest class
import java.util.Scanner; // Import the Scanner class
class TreeTest {
public static void main(String[] args) {
}
}
}
}
Exercises 1
1. Study the given code and complete the main method.
5
Tree Implementation using recursion
class BinaryNode{
int data;
BinaryNode left;
BinaryNode right;
public BinaryNode(int d) {
data=d;
left=right=null;
}
public int getData(){
return data;
}
}
public BinarySearchTree() {
root = null;
}
6
} else if (d > t.data) {
t.right = insertSubtree(t.right, d);
}
return t;
}
if (t == null)
return;
visit(t);
preorderSubtree(t.left);
preorderSubtree(t.right);
if (t == null)
return;
inorderSubtree(t.left);
visit(t);
inorderSubtree(t.right);
}
7
postorderSubtree(t.left);
postorderSubtree(t.right);
visit(t);
}
8
if (t == null)
return -1;
int h = heightSubtree(t.left);
int k = heightSubtree(t.right);
return (h > k) ? h + 1 : k + 1;
}
}
Exercise 2
1. Study the given code and write the main method.
2. Insert 45, 23, 60, 20, 18 into the binary search tree.
3. Print preorder traversal.
4. Delete 45.
5. Print preorder, postorder and inorder traversals.
6. Print height of the binary tree.