In NS2 or NS3, you need to understand the directory structure of the folder NS2/NS3 source code where NS2 uses C++ and NS3 uses Python. Then you need to choose which WSN protocol you going to add the backtracking algorithm to. Search for the .cc/.h file (NS2) or .py file (NS3) for that protocol and you add your code of the back-tracking algorithm (depending on the logic of the algorithm) in the file. Recompile using (Make then Make Install) and viola, that protocol next time you run the experiment will be running your backtracking algorithm.
PS: it is better to add enable Boolean and if statements to the parts you add, if you want to compare with the original protocol. so that in the experiments, you just enable it with a boolean