Improve logic for adding/removing nodes.