'Number of ways to delete a binary tree if only leaves can be deleted
I am solving an algorithm question:
You are given a binary tree
root. In one operation you can delete one leaf node in the tree. Return the number of different ways there are to delete the whole tree. So, if the tree is:
1
/ \
2 3
/
4
The expected answer is 3: [2, 4, 3, 1],[4, 2, 3, 1] and [4, 3, 2, 1].
I have been thinking hard, but I don't know how to formulate the recursive function. Thinking along the lines of the Climbing Stairs problem in which we count "distinct ways can you climb to the top", I think I have to use DP, but I am unable to formulate the recursive relation.
If you could provide some hints/guidance, I would appreciate it. Thanks!
Edit: Given the following tree:
1
/ \
2 3
/ \
4 5
There are 2 ways in which we could delete the children of 3 (4, 5); but how to use this info to determine the number of ways for root node 1? (The expected answer is 8).
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
