Created
April 10, 2017 15:16
-
-
Save jluismm2311/e80dbc89f4382345c0f2d2630fff1908 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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