Firstly, let’s ignore the third condition for now. Consider the tree is rooted at node 1. Let dpi be the number of valid sets contain node i and other nodes in the subtree of i. This can be easily calculated using a dfs: dpi=∏j∈child(i)(dpj+1)
Now consider the third condition. We can set each node to be the smallest value in the valid set respectively. After setting the smallest value, start dfs from node i and only visit nodes j such that ai≤aj≤ai+d. In this case, the third condition is satisfied so we can calculate the answer using the formula above. Also be careful with the duplicate counting, i.e. if aj=ai, only visit node j such that j>i.