I am trying to implement binary tree in java Here is my code for my binary tree implementation.I am gettng an error please help: I get an Error:nullpointException ! In my opinion the function construstBinaryTree should return binary tree not just a root!!! Thank you for anwser my question.
''' public class Print_Array_Binary {
public static void main(String[] args) {
int a[]={1,2, 3};
TreeNode root = construstBinaryTree(a);
System.out.println(root.left.val);// where I get an Error:nullpointException !
levelRead(root);
}
public static TreeNode construstBinaryTree(int [] nums){
TreeNode treeNodeArray[]=new TreeNode[nums.length];
Arrays.fill(treeNodeArray,null);
TreeNode root = null;
for (int i = 0; i < nums.length;i++) {
if(nums[i] != -1) {treeNodeArray[i] = new TreeNode(nums[i]);}
if(i == 0) { root = new TreeNode(nums[i]);}
}
System.out.print("二叉结点数组:");
for (TreeNode treeNode : treeNodeArray) {
System.out.print(treeNode.val+" ");
}
System.out.println();
//二叉树数组->二叉树
for (int i = 0; 2 * i + 2 < nums.length; i++){
if(treeNodeArray[i] != null) {
treeNodeArray[i].left = treeNodeArray[2 * i + 1];
treeNodeArray[i].right = treeNodeArray[2 * i + 2];
}
}
System.out.println(treeNodeArray[0].left.val);
System.out.println(treeNodeArray[0].right.val);
return root;
}
public static void levelRead(TreeNode root)
{
if(root == null) return;
Queue<TreeNode> queue = new LinkedList<TreeNode>() ;
queue.add(root);
while(queue.size() != 0)
{
int len = queue.size();
for(int i=0;i <len; i++)
{
TreeNode temp = queue.poll();
System.out.print(temp.val+" ");
if(temp.left != null) queue.add(temp.left);
if(temp.right != null) queue.add(temp.right);
}
}
}
}
'''