1469. Find All The Lonely Nodes
Last updated
Was this helpful?
Last updated
Was this helpful?
In a binary tree, a lonely node is a node that is the only child of its parent node. The root of the tree is not lonely because it does not have a parent node.
Given the root
of a binary tree, return an array containing the values of all lonely nodes in the tree. Return the list in any order.
Example 1:
Example 2:
Example 3:
Example 4:
Example 5:
Constraints:
The number of nodes in the tree
is in the range [1, 1000].
Each node's value is between [1, 10^6]
.
Tree
We collect node values from the views of their parents. In the DFS function, we do not consider any null nodes or leaf nodes since they have no children. Then, if the current node has only one child, we append the value of that child to the result array. At last, perform DFS on both left and right children. Because we only collect the value of input node's child, we can start DFS from root, which will not be collected.
Time complexity:
Space complexity: