Given a binary tree, return or print all the nodes that do not have siblings. A node does not have a sibling if it is the only child of its parent. If the tree is empty or every node has a sibling, return an empty list or indicate that no such nodes exist.
graph TD;
A(1) --- B(2) & C(3)
B --- D(4) & E(5)
C ~~~ N1:::hidden
C --- F(6):::ans
D --- G(7):::ans
D ~~~ N2:::hidden
E --- H(8):::ans
E ~~~ N3:::hidden
classDef hidden display:none
classDef ans fill:#1E90FF,stroke:#000,stroke-width:1px,color:#000;
1
2
3
Input: root =[1,2,3,4,5,null,6,7,null,8,null]Output: [6,7,8]Explanation: All the nodes in blue dont have siblings and hence part of answer.
⏰ Time complexity: O(n). Every node is visited once during traversal.
🧺 Space complexity: O(h). The maximum space used corresponds to the height h of the tree in a recursive implementation or to the breadth in a queue for BFS (O(n) in the worst-case balanced tree as h = log(n)).