enigma6174
enigma6174

Reputation: 360

How to insert recursively into Binary Tree and also print the elements recursively?

This is the Java program I wrote to create a Binary Tree and insert elements into it. However, I could not write the program for inserting the elements recursively and thus had to manually specify the left and right children respectively.

Here is my code:

public class BinTree {

private Node root;

private class Node {
Node left;
Node right;
int data;

private Node(int data) {
    this.data = data;
    left = null;
    right = null;
}
}
public BinTree() {
root = null;
}
public void preorder(Node temp) {
temp = root;
if(temp != null) {
    System.out.print(temp.data + " ");
    preorder(temp.left);
    preorder(temp.right);
}
}
public void add() {

root = new Node(10);
root.left = new Node(20);
root.right = new Node(30);
root.left.left = new Node(40);
root.left.right = new Node(50);
root.right.left = new Node(60);
}
public static void main(String[] args) {

BinTree bt = new BinTree();
bt.add();
System.out.print(bt.root.data);
System.out.print(" " + bt.root.left.data);
System.out.print(" " + bt.root.right.data);
System.out.print(" " + bt.root.left.left.data);
System.out.print(" " + bt.root.left.right.data);
}
}

Also, the preorder traversal I wrote for the above program failed and I got some unending output. Had to kill the execution!

Hence if some one could provide me the correct implementation of inserting elements into binary tree recursively it would be of great help.

Also, if possible, could you please tell me where i made a mistake in my preorder traversal?

Thanks in advance!

Upvotes: 1

Views: 168

Answers (1)

Codor
Codor

Reputation: 17605

To answer the question in part, the preorder function contains a bug as it does not actually traverse the tree but starts from the root over and over again. Change it to

public void preorder(Node temp)
{
    if(temp != null)
    {
        System.out.print(temp.data + " ");
        preorder(temp.left);
        preorder(temp.right);
    }
}

and call it with the root of the tree as an argument.

Upvotes: 2

Related Questions