void visitTree( struct TreeNode * t , struct TreeNode * form , int * x , int * y , int depth ){ if( t == NULL ){ return ; } if( t -> val == *x ){ *x = form -> val + depth * 1000; } //if the value of current node is equaling the value of assigned y, updating y if( t -> val == *y ){ *y = form -> val + depth * 1000; } //visitng the left and right child of t visitTree( t -> left , t , x , y , depth + 1 ); visitTree( t -> right , t , x , y , depth + 1 ); } bool isCousins( struct TreeNode * root , int x , int y ){ visitTree( root , root , &x , &y , 0 ); //making sure x and y in the same depth, and making sure they have different parents if( x % 1000 != y % 1000 && x / 1000 == y / 1000 ){ return true; } return false; }