In construction of binary tree it is giving null pointer Exception. how to solve it?
Doubt related binary tree
share your complete code here
package generictree; import java.util.Scanner; public class binarytree { class Node { int data; Node left; Node right; Node(int data,Node left,Node right) { this.data=data; this.left=left; this.right=right; } } private Node root=null; private int size=0; binarytree() { Scanner s = new Scanner(System.in); Node root = takeinput(s,null,false); } private Node takeinput(Scanner s,Node parent,boolean isleftorright ) {if(parent==null) { System.out.println(“enter the data for root node”); }else { if(isleftorright) { System.out.println(“enter the data for left child”+parent.data); } else { System.out.println(“enter the data for right child”+parent.data); } } int nodedata=s.nextInt(); Node node =new Node(nodedata,null,null); this.size++; boolean choice=false; System.out.println(“do you have left child of”+node.data); choice=s.nextBoolean(); if(choice) { node.left=takeinput(s,node,true); } choice = false; System.out.println(“do you have right child of”+node.data); choice=s.nextBoolean(); if(choice) { node.right=takeinput(s,node,false); } return node; } public void display() { this.display(this.root); } private void display(Node node) { String str=""; if(node.left!=null) { str=str+node.left.data+"=>"; } else { str=str+“END=>”; } str=str+node.data; if(node.right!=null) { str=str+"<="+node.right.data; } else { str=str+"<=END"; } System.out.println(str); if(node.left!=null) { this.display(node.left); } if(node.right!=null) { this.display(node.right); } } }
I have saved the code on ide
in line no 21 of your first link dont write Node root=takeInput(…)(it is creating local variable root)
just write root=takeInput(…)…
I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.
On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.