A Spruce Tree
You are given a tree with n nodes, rooted at node 1. A node is considered a "leaf" if it has no children. A tree is considered a "spruce" if EVERY non-leaf node has at least 3 direct children that are leaves. Your task is to determine if the given tree is a spruce and return "Yes" if it is, and "No" otherwise.
Array p: A 0-indexed array of length n - 1 representing the parent of each node. p[i] is the parent of Node i + 2. (e.g., p[0] is the parent of Node 2).
Vertex u is called a child of vertex v and vertex v is called a parent of vertex u if there exists a directed edge from v to u. A vertex is called a leaf if it doesn't have children and has a parent.
Example 1:
Input: n = 4, p = [1, 1, 1]
Output: Yes
Explanation: Node 1 has children 2, 3, and 4. Nodes 2, 3, and 4 have no children, so they are leaves. The only non-leaf node is 1, and it has exactly 3 leaf children. It is a spruce.
Example 2:
Input: n = 7, p = [1, 1, 1, 2, 2, 2]
Output: No
Explanation: Node 1 has children 2, 3, 4.
- Node 2 has children 5, 6, 7.
- Leaves are 3, 4, 5, 6, 7.
- Let's check non-leaves: Node 2 has 3 leaf children (5, 6, 7). But Node 1 only has 2 leaf children (3 and 4; node 2 is NOT a leaf). Since Node 1 fails the condition, the answer is No.
Now Your Turn!
Pick the correct output for the given inputInput : n = 8, p = [1, 1, 1, 1, 3, 3, 3]
Still unsure what the problem is asking ?
Let’s go through a few more examples, step by step, to make it clearer.
Constraints:
- 3 <= n <= 1000
- 1 <= pi <= i
- The root (node 1) is guaranteed to have at least 2 children.