Node *commonAncestor(Node *root, Node *node1, Node *node2) { if (root == nullptr || node1 == nullptr || node2 == nullptr) return nullptr; if (find(root->left, node1) && find(root->left, node2)) return commonAncestor(root->left, node1, node2); else if (find(root->right, node1) && find(root->right, node2)) return commonAncestor(root->right, node1, node2); else return root; }
int main(){ struct node *root = NULL; add(&root,4); add(&root,1); add(&root,3); add(&root,7); add(&root,9); add(&root,5); add(&root,8); add(&root,2); add(&root,6); struct node *b = NULL; add(&b,1); add(&b,2); add(&b,3); add(&b,4); add(&b,5); add(&b,6); add(&b,7); add(&b,8); add(&b,9); printf("\n\n Compare trees for similarity: %s \n\n", isSimilar(root,b) ? "true": "false"); printf("\n\ninorder:"); inorder(root); // printf("\nPREORDER: \n"); // preorderStack(root); printf("\nPOSTORDER: \n"); postOrderStack(root); struct node *lca_6_8 = commonAncestor(root,find(root,8),find(root,6)); printf("\n\nleast common ancestor: 6,8: %d\n", lca_6_8->data); struct node *lca_2_8 = commonAncestor(root,find(root,8),find(root,2)); printf("\n\nleast common ancestor: 2,8: %d\n", lca_2_8->data); struct node *lca_6_7 = commonAncestor(root,find(root,7),find(root,6)); printf("\n\nleast common ancestor: 6,7: %d\n", lca_6_7->data); int distance_6_8 = distance(root,find(root,8),find(root,6)); printf("\n\ndistance: 6,8: %d\n", distance_6_8); int distance_2_8 = distance(root,find(root,8),find(root,2)); printf("\n\ndistance: 2,8: %d\n", distance_2_8); int distance_6_7 = distance(root,find(root,7),find(root,6)); printf("\n\ndistance: 6,7: %d\n", distance_6_7); printf("\n\nzigazag:"); zigzag(root); printf("\n\n"); }
struct node* commonAncestor(struct node *root, struct node *a, struct node *b){ if(root == NULL){ return NULL; } struct node *t1 = commonAncestor(root->left,a,b); struct node *t2 = commonAncestor(root->right,a,b); struct node *t3 = root == a || root ==b ? root : NULL; int sum = (t1 == NULL ? 0 : 1) + (t2 == NULL ? 0 : 1) + (t3 == NULL ? 0 : 1); if(sum == 2) return root; return t1 != NULL ? t1 : (t2 != NULL ? t2 : t3); }