Requirements: Give a set of data to create a complete binary tree based on this set of data.
First, we know that the array subscript range is 0 to n-1, while the number in the tree starts from 1, and the subscript range is 1 to n;
according to the nature of the binary tree (a complete binary tree is numbered from top to bottom, from left to right, its number is the node of I, if 2*i<=n is met, then the node numbered I has left child, otherwise no, If 2*i+1<=n is satisfied, then the node with number I has right child, otherwise no)
2*i<=n
2*i+1<=n
The character is the number of the tree (1~N) is established, and the subscript of the array is from 0 to n-1, the corresponding subscript is reduced by 1, for the array 0~n-1,
2*i-1<=n-1
The 2*i<=n-1 was established.
take a closer look at whether the two new rules can be used directly, for 2*i-1<=n-1, when I=0, 2*i-1=-1, and 2*i-1 corresponding to what is it? is the number I node of the left child's number, apparently no node numbered-1 , then we try to 2*i-1+1 it, when I=0, 2*i-1=0, numbered 0 of the node corresponding to the left child obviously can not be itself, so on this basis add one, get the conclusion:
2*i-1+2=2*i+1<=n-1
2*i+2=2*i+2<=n-1
The following is the concrete realization of the idea:
malloc has a contiguous space, and each piece of space are a Binarytree Structural Body
1 //to create a complete binary tree from an array2#include <iostream>3#include <stdio.h>4 using namespacestd;5typedefstructTree6 {7 intvalue;8 structtree*Left ;9 structtree*Right ;Ten One }binarytree; Abinarytree* Create (intA[],intN) - { -BinaryTree *ptree= (binarytree*)malloc(sizeof(BinaryTree) *n); the inti; - for(i=0; i<n;i++) - { -Ptree[i].value=A[i]; //array A only functions as an assignment +ptree[i].left=NULL; -ptree[i].right=NULL; + } A for(i=0; i<=n/2-1; i++)//The original Father node range is 1~N/2, now 0~n/2-1, so note n/2 to take at { - if(2*i+1<=n-1) - Ptree[i].left=&Ptree[2*i+1]; //Assign the address of the first 2*i+1 node to the left child. - if(2*i+2<=n-1) - Ptree[i].right=&Ptree[2*i+2]; - } in returnPtree; - } to voidPreorder (binarytree*t) + { - if(T==null)return ; theprintf"%d\n",t->value); *Preorder (t->Left ); $Preorder (t->Right );Panax Notoginseng } - intMain () the { + inta[]={3,4,5,8,9,Ten}; ABinaryTree *root=NULL; theRoot=create (A,sizeof(a)/sizeof(a[0])); + - preorder (root); $ return 0; $}
-
Binary tree----To create a complete binary tree from an array