Skip to content

Instantly share code, notes, and snippets.

@caigen
Created October 13, 2014 13:08
Show Gist options
  • Save caigen/1711ad28dd0a6d0908f4 to your computer and use it in GitHub Desktop.
Save caigen/1711ad28dd0a6d0908f4 to your computer and use it in GitHub Desktop.
decide if binary tree a contains binary tree b?
#include <iostream>
using namespace std;
typedef struct _node {
_node* left;
_node* right;
char c;
}node;
// it does not mean exactly match.
// it means that all b's nodes are equal with a's corresponding nodes.
bool tree_match(node *a, node* b) {
if (b == NULL) {
return true;
}
else if (a == NULL) {
return false;
}
if (b->left == NULL && b->right == NULL && b->c == a->c) {
return true;
}
if (a->c == b->c && tree_match(a->left, b->left) && tree_match(a->right, b->right)) {
return true;
}
return false;
}
// go through all nodes.
bool contains(node* a, node*b) {
if (tree_match(a, b)) {
return true;
}
else if (tree_match(a->left, b) || tree_match(a->right, b)) {
return true;
}
return false;
}
int main(int argc, char* argv[]) {
node* a = new node;
a->left = new node;
a->right = new node;
a->c = 'A';
a->left->left = a->left->right = NULL;
a->left->c = 'B';
a->right->left = a->right->right = NULL;
a->right->c = 'C';
// a
// /\
// b c
// /\/\
// ####
node* b = new node;
b->c = 'B';
b->left=b->right=NULL;
// b
// /\
// # #
if (contains(a,b)) {
cout << "yes" << endl;
}
else {
cout << "no" << endl;
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment