1. 程式人生 > >劍指offer-------把二叉樹列印成多行

劍指offer-------把二叉樹列印成多行

題目:

思路:

程式碼:

struct TreeNode
{
	int val;
	TreeNode *left;
	TreeNode *right;
}

void Print(BinaryTreeNOde* pRoot)
{
	if(pRoot == NULL)
		return;
	
	queue<BinaryTreeNOde*>nodes;
	nodes.push(pRoot);
	
	int nextlevel=0;
	int toPrinted=1;
	
	while(!nodes.empty())
	{
		BinaryTreeNOde* pNode=queue.front();
		printf("%d",pNode->val);
		
		if(pNode->left!=NULL)
		{
			nodes.push(pNode->left);
			nextlevel++;
		}
		
		f(pNode->right!=NULL)
		{
			nodes.push(pNode->right);
			nextlevel++;
		}
		
		nodes.pop();
		--toPrinted;
		
		if(toPrinted==0)
		{
			printf("\n");
			toPrinted=nextlevel;
			nextlevel = 0;
		}
	}
}