剑指offer——分行从上到下打印二叉树(32题)

题目:分行从上到下打印二叉树,从上到下按层打印二叉树,同一层的节点按从左到右的顺序打印,每一层打印至一行。

解决二叉树的遍历问题无外乎就是三种遍历方法,此处增加了按层遍历的条件,即广度优先遍历。解决广度优先遍历,首先想到运用队列。同理,解决深度优先遍历,首先想到到家用递归。想必这是常识,应形成条件反射。

该题目的特点是分行哈,可通过设置每行元素个数标志来实现。具体代码见下:

#include<iostream>
#include<queue>

using namespace std;

/*
分行从上到下打印二叉树(特点是分行哈,可通过设置每行元素个数标志来实现)
*/
struct TreeNode {
	int val;
	TreeNode* left, *right;
	TreeNode(int x):val(x),left(nullptr),right(nullptr){}
};

void print(TreeNode* root) {
	if (!root)
		return;
	queue<TreeNode*> nodes;
	nodes.push(root);
	int nextLevel = 0;//统计每行的元素个数
	int toBePrinted = 1;//每输出一行的一个元素时,将值减1,直至为0时,进行换行
	while (!nodes.empty()) {
		TreeNode* cur = nodes.front();
		nodes.pop();
		cout << cur->val << " ";
		if (cur->left) {
			nodes.push(cur->left);
			++nextLevel;//遍历到每一行的元素时,其行内的元素总个数进行加1
		}
		if (cur->right) {
			nodes.push(cur->right);
			++nextLevel;
		}
		--toBePrinted;//每输出一个行内元素时,将个数进行减1

		if (toBePrinted == 0) {//表有该换行啦
			cout << endl;
			toBePrinted = nextLevel;
			nextLevel = 0;
		}
	}
}

猜你喜欢

转载自blog.csdn.net/TT_love9527/article/details/82753625