What is the error in my code?

import java.util.*;

class Main{
static class Node{
int data;
Node left;
Node right;

Node(int data){
this.data = data;
left = right = null;
}

}
static Node root = null;

public static Node createTree(int[] arr,int lo, int hi)
{
if(lo>hi) return null;

if(lo == hi){
    Node base = new Node(arr[lo]);
    return base;
}

int mid = (lo+hi)/2;

Node nn = new Node(arr[mid]);

nn.left = createTree(arr,lo,mid-1);
nn.right = createTree(arr,mid+1,hi);

return nn;

}

public static Node replace(Node node,int Max){
if(node == null) return null;

node.right = replace(node.right,Max);
if(node.data > Max){
   Max += node.data ;
}
if(Max > node.data){
    node.data = node.data + Max;
    Max = node.data;
}
node.left = replace(node.left,Max);

return node;

}

public static void preOrder(Node node){
if(node == null) return;

System.out.print(node.data+" ");

preOrder(node.left);

preOrder(node.right);

}
public static Scanner scn = new Scanner(System.in);
public static void main(String[] args){

int n = scn.nextInt();
int [] arr = new int [n];
for(int i = 0; i<n; i++)
arr[i]= scn.nextInt();

root = createTree(arr,0,arr.length-1);

root = replace(root,0);

preOrder(root);

}
}

@ap8730390,
In the submissions, it shows that you have got a correct answer for the question. Do you have any further doubts regarding the question?

It’s not working for the code I asked in the doubt section. It’s working for my modified code. I want to know why it was not working in my previous code

One more thing I wanted to ask was can’t I submit code in cpp? Like the same code worked for Java but when I tried to submit code in cpp, it showed compilation error

@ap8730390,
It is not working for the code you sent because max should be global. Max variable should not be passed as an argument. There might be some error in the code, that’s why the compilation error

Okay ! I found my error. Sorry :slight_smile:

1 Like