Easy solution:
This is a standard approach of implementation using pre-order traversal:
void pre_order(struct TreeNode *nd, int *res, int *rs);int* getLonelyNodes(struct TreeNode* root, int* returnSize){ int *res;
if (!root)
return NULL;
(*returnSize) = 0;
res = (int *)malloc(1000*sizeof(int));
// todo check
pre_order(root, res, returnSize);
return res;
}void pre_order(struct TreeNode *nd, int *res, int *rs){
if (!nd)
return;
if (nd->left && !nd->right)
res[(*rs)++] = nd->left->val;
if (nd->right && !nd->left)
res[(*rs)++] = nd->right->val;
pre_order(nd->left, res, rs);
pre_order(nd->right, res, rs);
return;
}