[C ++] - array is converted into a binary tree

Data structure has been on the poor, those trees have been confused array of nodes and how is one to one up, write the next blog organize their own ideas.

The definition of a binary tree

Binary tree is a very nonlinear structural use, having the following two characteristics:

  1. Only a non-empty binary tree root
  2. Each node has at most two sub-tree, the nodes are called the left and right subtree subtree

The nature of binary tree

1 Properties : k-th layer in the binary tree, up to 2k-1 (k> = 1 ) nodes
properties 2 : m binary tree depth up to 2m-1 nodes
properties 3 : In any one binary tree, reading for the node (i.e., is a leaf node) is better than 0 degrees to a plurality of nodes 2
Property 4 : the binary tree has n nodes and a depth of at least [log2n] +1, where [log2n] represents taking integer part of log2n

Turned into an ordered array of binary steps:

As will be sorted array [1,2,3,4,5,6,7,8,9] into a binary


// - 首先定义每一个节点,每个节点包括自身值,左节点和右节点
struct Node
{
	int data;
	Node* _left;
	Node* _right;
}node;

 //- 采用递归的方法创建二叉树

typedef Node* bitree;
void BuildTree(bitree &T, int*a, int begin, int end)
{
	if (begin > end)
		return;
	int mid = (begin + end) / 2;
	if (T == NULL)  //为当前树的根结点申请空间
	{
		T = (Node*)malloc(sizeof(Node));
		T->data = a[mid];
		T->_left = NULL;
		T->_right = NULL;
	}
	BuildTree(T->_left, a, begin, mid - 1);
	BuildTree(T->_right, a, mid+1, end);
}
Published 33 original articles · won praise 13 · views 1053

Guess you like

Origin blog.csdn.net/Vicky_Cr/article/details/104451216