Can someone post its recursive solution please?


#1

Comment body goes here.


#2

bool helper(vector &A , int root ,int ed )
{
if(root >= ed)
return 1;
int index = upper_bound( A.begin() +root , A.begin()+ed, A[root] ) - A.begin();
for(int i = root+1 ; i< index ; i++)
{
if(A[i] > A[root])
return 0;
}
for( int i = index ; i < ed ; i++)
{
if(A[i] < A[root])
{
return 0;
}
}

return helper(A , root+1 , index-1) && helper(A , index , ed);

}

int Solution::solve(vector &A) {

// int root = 0;
// int index = upper_bound( A.begin() +1 , A.begin()+3, 5 ) - A.begin();
// cout<< index;
return helper(A , 0 , A.size()-1);

}


#3

public class Solution {
int ans = 1;
TreeNode tree;
public int solve(int[] preorder) {

    tree = new TreeNode(preorder[0]);
    for(int i = 1;i < preorder.length; i++){
        if(ans == 1)
            tree = recc(tree, preorder[i]);
    }
    
   return ans;
}

private TreeNode recc(TreeNode A, int n){
    
    if(n < A.val && A.right != null){
        ans = 0;
        return A;
    }
    
    else if(n < A.val && A.right == null){
        if(A.left == null)
            A.left = new TreeNode(n);
        else
            recc(A.left, n);
    }
    
    else if(n > A.val){
        if(A.right == null)
            A.right = new TreeNode(n);
        else
            recc(A.right, n);
    }
        
return A;
}

}


#4
int solver(vector<int> &A, int &indx, int L=-INT_MAX, int R=INT_MAX){
if (indx >= A.size())
    return 1;
if( !(L<A[indx] && A[indx]<=R) )  //root
    return 0;

int end = A[indx];
solver(A,++indx,L,end); //go left
return solver(A,indx,end,R); // go right

}