根据完全二叉树的数组以非递归方式创建二叉树

在网上找了很多非递归方式创建二叉树的方法,但大多都不是根据完全二叉树的数组来创建的。这道题难点在于创建到叶子节点的时候,此时应该要返回到他的兄弟节点进行创建。一开始我想着用一个int flag标志和temp节点保存兄弟节点以便返回,但实际实现起来相当复杂。

        最后我的方法是先创建一个二叉树节点数组,这个数组只保存了自己的数据,lchild和rchild都是NULL。然后再遍历这个数组,把每个节点相互连接起来。

输入样例:

3
ABC0D
ABCDEF000G
ABEC0F0D0

输出样例:

ABDC
ABDEGCF
ABCDEF

#include <iostream>
#include <string>
#include <stack>
using namespace std;
typedef struct node {
	char data;
	struct node* lchild, * rchild;
}node;
void CreateNode(node *&P,char c)
{
	P = new node;
	if (c != '0')
	{
		P->data = c;
		P->lchild = NULL;
		P->rchild = NULL;
	}
	else
		P = NULL;
}
void Create(node*&root, string s) {
	int i = 1, size = s.length();
	node* st[100];
	node * temp;
	root = new node;
	CreateNode(root, s[0]);
	st[0] = root;
	temp = root;
	for(i;i<size;i++)
	{
		CreateNode(temp, s[i]);
		st[i] = temp;				//先把每个节点按所给数组的顺序放入st中
									//此时st数组中每个节点的左孩子右孩子都是NULL
	}
	for (int k = 0; k < size; k++) {//让每个节点都认领孩子
		int j = k * 2 + 1;
		if (st[k])
		{
			if (j < size)
			{
				st[k]->lchild = st[j];   //类似链表节点的相互连接
			}
			j++;
			if (j < size)
			{
				st[k]->rchild = st[j];
			}
		}
	}
}
void PreOrder(node* P)
{
	stack<node*>s;
	s.push(P);
	node* temp = new node;
	while (!s.empty())
	{
		temp = s.top();
		s.pop();
		if (temp != NULL)
		{
			cout << temp->data;
			s.push(temp->rchild);
			s.push(temp->lchild);
		}
	}
}
int main() {
	int t;
	cin >> t;
	while (t--) {
		string s;
		node* P = new node;
		cin >> s;
		Create(P, s);
		PreOrder(P);
		cout << endl;
	}
}

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值