Exemplo n.º 1
0
 int main(){
     int preorder[] = {'A', 'B', 'D', 'J', 'K', 'E', 'L', 'C', 'F', 'H', 'M'};
     int inorder[] = {'J', 'D', 'K', 'B', 'E', 'L', 'A', 'F', 'C', 'M', 'H'};

     node* root = build_binary_tree(preorder, inorder, sizeof(inorder)/sizeof(inorder[0]));
     tranverse_tree_preorder(root);
     cout << endl;
 }
Exemplo n.º 2
0
int main(int argc,char *argv[])
{
	tree *t;
	build_binary_tree(&t,argv[1],0,strlen(argv[1])-1);
	print_tree(t,"root");

	return 0;
}
Exemplo n.º 3
0
 /*
  * @func: rebuild the binary tree, according to preorder and inorder.
  * @params: pre {int*}, the preorder list of binary tree
  *          mid {int*}, the inorder list of binary tree
  *          cnt {int}, the element count of binary tree
  * @return: node*, the root of binary tree
  */
 node* build_binary_tree(const int* pre, const int* mid, const int cnt){
     if (pre == NULL || mid == NULL || cnt == 0)
             return NULL;

     node* root = new node;
     root->data = pre[0];

     int left_len = 0;
     while(mid[left_len] != root->data)
             ++left_len;
     int right_len = cnt - left_len - 1;

     root->left = build_binary_tree(pre+1, mid, left_len);
     root->right = build_binary_tree(pre+left_len+1, mid+left_len+1, right_len);

     return root;
 }
Exemplo n.º 4
0
void build_binary_tree(tree **root,char *arr,int left,int right)
{
	tree *new_node;
	printf("left:%d right:%d middle:%d\n",left,right,arr[(left+right)/2]-'0');
	int middle;
	/*if(*root==NULL)
		return;*/
	if(left>right)
		return;
	
	middle=left+(right-left)/2;
	new_node=malloc(sizeof(struct tree_node));
	if(new_node==NULL)
		return;
	new_node->element=arr[middle]-'0';
	new_node->left=new_node->right=NULL;
	
	*root=new_node;
	build_binary_tree(&((*root)->left),arr,left,middle-1);
	build_binary_tree(&((*root)->right),arr,middle+1,right);
}