静态链表表示二叉树

静态链表就是利用数组来模拟一个链表存储,所以需要一个游标来指示下一个元素存储在数组哪儿(即指示了下一个元素的下标)。

下面的程序就是利用一个静态链表来存储了一个二叉树(二叉树的结构如图所示):

静态链表表示二叉树_第1张图片

具体代码如下:

#include 

using namespace std;

typedef struct
{
	char data;
	int left;
	int right;
} static_node;

void pre_order_traverse(static_node* binary_tree, int index)
{

	if (index == -1)
	{
		return;
	}
	cout << binary_tree[index].data << " ";

	pre_order_traverse(binary_tree, binary_tree[index].left);

	pre_order_traverse(binary_tree, binary_tree[index].right);
}

int main()
{
	static_node binary_tree[7];

	binary_tree[0].data = 'a';
	binary_tree[0].left = 1;
	binary_tree[0].right = 2;

	binary_tree[1].data = 'b';
	binary_tree[1].left = 3;
	binary_tree[1].right = -1;

	binary_tree[2].data = 'c';
	binary_tree[2].left = 4;
	binary_tree[2].right = 5;

	binary_tree[3].data = 'd';
	binary_tree[3].left = -1;
	binary_tree[3].right = 6;

	binary_tree[4].data = 'e';
	binary_tree[4].left = -1;
	binary_tree[4].right = -1;

	binary_tree[5].data = 'f';
	binary_tree[5].left = -1;
	binary_tree[5].right = -1;

	binary_tree[6].data = 'g';
	binary_tree[6].left = -1;
	binary_tree[6].right = -1;

	pre_order_traverse(binary_tree, 0);
	cout << endl;
	
	return 0;
}

前序输出结果是:“a b d g c e f”

你可能感兴趣的:(C++)