[编程之美]分层遍历二叉树

编程之美提供了两个方法:递归和用vector来保存遍历结果;但是第二种用vector的方法需要保存下所有节点,是o(n)的空间复杂度。

下面是自己的一个的方法,利用与BFS类似的思想,借助一个栈可以使空间复杂度降到 O(M),M表示具有最多节点的那层的节点数,最坏情况下 M = N/2;

 

void BFSTree(node* tree)
{
	if (! tree) return;
	queue<node*> Q;
	Q.push(tree);
	int num=1;
	while(!Q.empty())
	{
		int next=0;
		while(num--)
		{
			node* t=Q.front();
			Q.pop();
			cout << t->val<<" ";
			if (t->lchild)
			{
				next++;
				Q.push(t->lchild);
			}
			if (t->rchild)
			{
				next++;
				Q.push(t->rchild);
			}
		}
		cout << endl;
		num=next;
	}
}

int main()
{
	vector<node> tree;
	tree.reverse(9);
	for(int i=1;i<=n;i++)
		tree.push_back(node(i));
	tree[1].lchild=tree[2];
	tree[1].rchild=tree[3];
	tree[2].lchild=tree[4];
	tree[2].rchild=tree[5];
	tree[5].lchild=tree[7];
	tree[5].rchild=tree[8];
	tree[3].rchild=tree[6];

	node* root= tree[1];
	BFSTree(root);
	system("pause");
}


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值