Exemplo n.º 1
0
int main() {
	int sum = 23;
	
 
/* 
  	Constructed binary tree is
            10
          /   \
        8      2
      /  \    /
    3     5  2
   /
  4
*/
    node *root = newnode(10);
  	root->left        = newnode(8);
  	root->right       = newnode(2);
  	root->left->left  = newnode(3);
  	root->left->right = newnode(5);
  	root->right->left = newnode(2);
  	root->left->left->left = newnode(4);

 	/*if( path_sum(root, sum, 0) ) {
 		printf("path exists!\n");
 		int i = 0;
 		for( ; i<10; i++ ) {
 			printf("%d\t", path[i]);
 		}
 	} else {
 		printf("no sum path.\n");
 	}*/
 	print_ancestors(root, 2);
 	//print_ancestors(path, 10);
	return 0;
}
Exemplo n.º 2
0
bool print_ancestors(node *root, int target)
{
  /* base cases */
  if (root == NULL)
     return false;
 
 	printf("now processing %d\n", root->data);
  if (root->data == target)
     return true;
 
  /* If target is present in either left or right subtree of this node,
     then print this node */
  if ( print_ancestors(root->left, target) ||
       print_ancestors(root->right, target) )
  {
    printf("%d part of path\n", root->data);
    return true;
  }
 
  /* Else return false */
  return false;
}
Exemplo n.º 3
0
void print_node_ancestor(bstn *root, int data, int data2)
{
	bstn static *ancestors[100]={NULL};
	int static data1_found=0;
	int static data2_found=0;
	if(root!=NULL)
	{
		if(root->data==data)
		{
			int count=0;
			while(ancestors[count]!=NULL)
			{
				data1_ancestors[count]=ancestors[count]->data;;
				count++;
			}
			data1_found=1;
			print_ancestors(ancestors);
		}

		if(root->data==data2)
		{
			int count=0;
			while(ancestors[count]!=NULL)
			{
				data2_ancestors[count]=ancestors[count]->data;
				count++;
			}
			data2_found=1;
			print_ancestors(ancestors);
		}

		int count=0;
		while(ancestors[count]!=NULL)
			count++;
		ancestors[count]=root;

		if(root->lnp!=NULL)
			 print_node_ancestor(root->lnp, data, data2);
		
		if(root->rnp!=NULL)
			 print_node_ancestor(root->rnp, data, data2);

		count=0;
		while(ancestors[count]!=NULL)
			count++;
		ancestors[count-1]=NULL;
	}

	if(data1_found && data2_found)
	{
		int count=0;
		int min=data1_ancestors[count];
		while(data1_ancestors[count]==data2_ancestors[count])
		{
			if(data1_ancestors[count]<min)
				min=data1_ancestors[count];
			count++;
		}
		printf("min ancestor found:%d\n", min);
	}
}