Skip to content

Instantly share code, notes, and snippets.

@jluismm2311
Created April 10, 2017 15:16
Show Gist options
  • Save jluismm2311/e80dbc89f4382345c0f2d2630fff1908 to your computer and use it in GitHub Desktop.
Save jluismm2311/e80dbc89f4382345c0f2d2630fff1908 to your computer and use it in GitHub Desktop.
import java.util.*;
public class Solution {
static TreeNode arrayToTree(int[] array) {
TreeNode root = null;
if(array.length > 0){
Queue<TreeNode> queue = new LinkedList<TreeNode>();
TreeNode treeNode = new TreeNode(array[0]);
queue.add(treeNode);
root = treeNode;
int index=0;
while(!queue.isEmpty()) {
TreeNode iterate = queue.poll();
index++;
if(index < array.length) {
TreeNode left = new TreeNode(array[index]);
queue.add(left);
iterate.left = left;
}
index++;
if(index < array.length) {
TreeNode right = new TreeNode(array[index]);
queue.add(right);
iterate.right = right;
}
}
}
return root;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment