I want to create a binary search tree tool in which it outputs all the nodes including the null In my current code, it only create nodes in the input array including its left and child then print
Is it possible to print all nodes including in a null like shown below? input = {23, 5, 2, 89, 56, 43} output = {23, 5, 89, 2, null, 56, null, null, null ,null ,null, null, 43, null}
public class Node {
int value;
Node right,left;
Node(){
value = 0;
left = null;
right = null;
}
Node(int i) {
value = i;
left = null;
right = null;
}
public void setLeft(Node newValue){
this.left = newValue;
}
public void setRight(Node newValue){
this.right = newValue;
}
public int getValue(){
return value;
}
public String getValueStr(){
return Integer.toString(value);
}
public void printAll(){
System.out.println("Value: "+ this.value
+"\nLeft: "+ this.left
+"\nRight: "+ this.right);
}
public void addChildToArr(ArrayList<String> arr){
arr.add(right.getValueStr());
arr.add(this.left.getValueStr());
}
public String getChildRightStr(){
if(right == null)
return "null";
else
return this.right.getValueStr();
}
public String getChildLeftStr(){
if(left == null)
return "null";
else
return this.left.getValueStr();
}
}
public class BST {
private static Node root;
ArrayList<Node> nodes = new ArrayList<>();
public BST(){
root = null;
}
public void insert(int data)
{
root = insert(root, data);
}
/* Function to insert data recursively */
private Node insert(Node node, int data)
{
if (node == null)
node = new Node(data);
else
{
if (data <= node.getValue()){
node.left = insert(node.left, data);
//nodes.add(node.left);
}
else{
node.right = insert(node.right, data);
//nodes.add(node.left);
}
}
if(!(nodes.contains(node)))
nodes.add(node);
return node;
}
public void printNodes(){
for(int i = 0; i < nodes.size();i++){
System.out.print(nodes.get(i).getChildLeftStr()+" ,"+nodes.get(i).getChildRightStr()+", ");
}
System.out.println("");
}
public void printNodeObj(){
for(int i = 0; i < nodes.size();i++){
System.out.println(nodes.get(i));
}
}
public int countNodes()
{
return countNodes(root);
}
/* Function to count number of nodes recursively */
private int countNodes(Node r)
{
if (r == null)
return 0;
else
{
int l = 1;
l += countNodes(r.getLeft());
l += countNodes(r.getRight());
return l;
}
}
public static void main(String[] args) {
BST bst = new BST();
int[] arr = {23,5,2,89,56,43,38,10,65,72};
System.out.print("["+arr[0]+", ");
for(int i = 0; i< arr.length;i++)
bst.insert(arr[i]);
bst.printNodes();
}
}
Thanks for the help.