0% found this document useful (0 votes)
21 views

Binary Tree

This is a java program

Uploaded by

Dude Raj
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views

Binary Tree

This is a java program

Uploaded by

Dude Raj
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 2

public class BinaryTree extends TreeNode {

TreeNode root;
public BinaryTree() {
root = null;
}

public void insert(int data) {


root = BinaryTree_NodeInsertion.insert(root, data);
}

public boolean isEmpty() {


return root == null;
}

public void traverse() {


print("traversal");
}

public void print() {


print("printing");
}

private void print( String s ) {


System.out.println("\nPreorder " + s + " of given Tree is : ");
preorder();
System.out.println("\nInorder " + s + " of given Tree is : ");
inorder();
System.out.println("\nPostorder " + s + " of given Tree is : ");
postorder();
}

public void addData(int... data) {


for ( int i : data )
insert(i);
}

public int count() {


return countNodes(root);
}

private int countNodes (TreeNode r) {


if (r == null)
return 0;
else {
int l = 1;
l += countNodes(r.getLeft());
l += countNodes(r.getRight());
return l;
}
}

public void inorder() {


inorder(root);
}

private void inorder( TreeNode root ) {


if (root != null) {
inorder(root.left);
System.out.print(root.getData() + " ");
inorder(root.getRight());
}
}

public void preorder() {


preorder(root);
}

private void preorder( TreeNode root ) {


if (root != null) {
System.out.print(root.getData() + " ");
preorder(root.getLeft());
preorder(root.getRight());
}
}

public void postorder () {


postorder (root);
}

private void postorder( TreeNode root ) {


if (root != null) {
postorder(root.getLeft());
postorder(root.getRight());
System.out.print(root.getData() + " ");
}
}

public void delete(int key) {


root = BinaryTree_NodeDeletion.delete(root, key);
}

public boolean Search(int value) {


return Search(root, value);
}

public static boolean Search(TreeNode root, int val) {


boolean flag = false;
while ( (root != null) && !flag) {
int rval = root.getData();
if ( val < rval)
root = root.getLeft();
else if (val > rval)
root = root.getRight();
else {
flag = true;
break;
}
flag = Search(root, val);
}
return flag;
}
}

You might also like