algorithm - Counting the number of unival subtrees in a binary tree -
i came across interview question of finding number of unival subtrees in binary tree. how can done?
int countunivals(node* head, bool* unival) { if (!node) { *unival = true; return 0; } bool unil,unir; int sum = countunivals(head->l, &unil) + countunivals(head->r, &unir); if (unil && unir && (!head->l || head->l->val == head->val) && (!head->r || head->r->val == head->val)) { sum++; *unival = true; } return sum; }
Comments
Post a Comment