May 07, 2020

How to convert an array into a tree datastructure in java

We have an array of n numbers for example

arr = { 1, 2, 3, 4 };

Our idea is to convert the array to a Tree data structure.

Solution is given below


How to convert an array into a tree datastructure in java


/**
 * How to convert an array into a tree datastructure in java
 */
package com.leetcode.algorithms;

/**
 * @author Konzernites
 *
 */
public class InsertionList {

/**
* @param args
*/
public static void main(String[] args) {
int[] arr = { 1, 2, 3, 4 };
InsertionList in = new InsertionList();
ListNode node = null;
for (int i = 0; i <= arr.length; i++) {
node = in.insert(node ,arr[i]);
}
System.out.println(node);
}

private ListNode insert(ListNode node, int data) {
if(null == node) {
return new ListNode(data);
}else {
node.next = insert(node.next, data);
}
return node;
}}


How to print a Tree in Java ?

Consider ListNode a Tree, the java code for ListNode is below.

You need to span each node of the tree still element exist. so the best control structure to be used here is the while loop.


  ListNode tree;
while(tree!=null) {
System.out.print(tree.val+" ");
tree=tree.next;
}


ListNode Java Class

public class ListNode{
int data;
ListNode next;
ListNode(int data){
this.data = data;
next = null
}}

Thank you...

No comments:

Post a Comment

Your feedback may help others !!!

Facebook comments