public class Tree { Node root;
// Tree Node
static class Node {
int data;
Node left, right;
Node(int data)
{
this.data = data;
this.left = null;
this.right = null;
}
@Override public String toString() {
return String.valueOf(data);
}
}
// Function to insert nodes in level order
public Node insertLevelOrder(int[] arr, Node root,
int i)
{
// Base case for recursion
if (i < arr.length) {
Node temp = new Node(arr[i]);
root = temp;
// insert left child
root.left = insertLevelOrder(arr, root.left,
i + 1);
// insert right child
//root.right = insertLevelOrder(arr, root.right,
// 2 * i + 2);
//System.out.println(root);
}
return root;
}
// Function to print tree nodes in InOrder fashion
public void inOrder(Node root)
{
if (root != null) {
inOrder(root.left);
System.out.print(root.left + " ");
//inOrder(root.right);
}
}
// Driver program to test above function
public static void main(String args[])
{
Tree t2 = new Tree();
int arr[] = {9,5,0,-3,-10};
t2.root = t2.insertLevelOrder(arr, t2.root, 0);
t2.inOrder(t2.root);
}
}
I don know if those nodes are been inserted or not, but the output return me right thing. I would like insert nodes only to the left child, can I eliminate that code? root.right = insertLevelOrder(arr, root.right, 2 * i + 2);
And also why this loop doesn't have a sign that "i++", how does int i increase automatically?