#C8030. Nodes Without Siblings
Nodes Without Siblings
Nodes Without Siblings
Given a binary tree represented in level order, find and return all the nodes that do not have any siblings. A node is considered to have no sibling if its parent has exactly one child. In other words, for a node with parent P, if either the left or right child of P is missing, then the existing child is to be included in the output.
For example, consider the following cases:
- Example 1: For a tree with level order:
1 2 3 4 -1 -1 -1
, the output is4
because the only node without a sibling is the left child of node 2. - Example 2: For a tree with level order:
1 2 3 4 -1 5 6 -1 -1 -1 7 -1 -1
, the output is4 7
since node 4 (child of 2) and node 7 (child of 5) have no siblings.
The binary tree is built using level order traversal where a missing child is denoted by -1
. The condition for a node n to have no sibling can be summarized in LaTeX as follows:
\( (\text{if } n \text{ is the left child then } n.parent.right = \text{null}) \quad \text{or} \quad (\text{if } n \text{ is the right child then } n.parent.left = \text{null}) \).
inputFormat
The input is provided as a single line of space-separated integers representing the level order traversal of a binary tree. The first integer represents the root. For any node, if a left or right child is missing, it is denoted by -1
. For example:
1 2 3 4 -1 -1 -1
represents a tree where the root is 1, its left child is 2, right child is 3, and node 2 has a left child 4.
outputFormat
Output a single line with space-separated integers corresponding to the node data of all nodes that do not have any siblings. If no such nodes exist, output an empty line.
## sample1 2 3 4 -1 -1 -1
4