剑指offer 32-2-把二叉树打印成多行 C++

16 篇文章 0 订阅

题目描述
从上到下按层打印二叉树,同一层结点从左至右输出。每一层输出一行。

思路1:非递归,层次遍历BFS,使用一个队列,每一层使用一个数组存储数据,分行打印

class Solution {
public:
	vector<vector<int> > Print(TreeNode* pRoot) {
		vector<vector<int>> res;
		vector<int> arr;
		if (pRoot == nullptr)
			return res;
		queue<TreeNode*> q;  //使用一个队列按层遍历元素
		q.push(pRoot);
		while (!q.empty())
		{
			int size = q.size();   //记录每一层的节点总个数
            arr.clear();   //遍历完一层后记得clear
			for (int i = 0; i < size; i++) {
				TreeNode* tmp = q.front();
				arr.push_back(tmp->val);
				q.pop();
				if (tmp->left)
					q.push(tmp->left);
				if (tmp->right)
					q.push(tmp->right);
			}
			res.push_back(arr);
		}
		return res;
	}
};

思路2:按顺序打印多行二叉树,用两个队列交错打印
【按之字形打印,可以用两个栈实现。】

class Solution {
public:
	vector<vector<int> > Print(TreeNode* pRoot) {
		vector<vector<int> > res;
		vector<int> arr;
		if (pRoot == nullptr)
			return res;
		queue<TreeNode*> q1;
		queue<TreeNode*> q2;
		q1.push(pRoot);
		while (!q1.empty() || !q2.empty())
		{
			TreeNode* tmp = nullptr;
			arr.clear();
			while (!q1.empty())
			{
				tmp = q1.front();   //q1中为当前层所有节点
				arr.push_back(tmp->val);
				q1.pop();
				if (tmp->left)
					q2.push(tmp->left);   //q2中为push进下一层的所有节点
				if (tmp->right)
					q2.push(tmp->right);
			}
			if (arr.size() != 0)
				res.push_back(arr);
			arr.clear();
			while (!q2.empty())
			{
				tmp = q2.front();
				arr.push_back(tmp->val);
				q2.pop();
				if (tmp->left)
					q1.push(tmp->left);
				if (tmp->right)
					q1.push(tmp->right);
			}
			if (arr.size() != 0)
				res.push_back(arr);
		}
		return res;
	}
};

思路3:利用递归的方法进行先序遍历,传递深度。递归深入一层扩容一层数组,先序遍历又保证了同层节点按从左到右入数组
>>>描述:假如一个二叉树 [1,2,3],当进入2时会创建一个 temp,此时 depth = 2,size=2;当2遍历完后会进入3,此时3 就不用创建 temp了,因为 2,3是同一层的,并且此时 depth==size 。

class Solution {
public:
	vector<vector<int>> Print(TreeNode * pRoot)
	{
		vector<vector<int>>result;
		Print(pRoot, 1, result);
		return result;
	}
	void Print(TreeNode * pRoot, int depth, vector<vector<int>>& data)
	{
		if (pRoot == nullptr)
			return;
		if (data.size() < depth)   //这个判断是用来让最左的元素创建 temp,而同一层后边的元素共用这个 temp
		{
			vector<int> temp;
			data.push_back(temp);
		}
		data[depth - 1].push_back(pRoot->val);
		Print(pRoot->left, depth+1,data);
		Print(pRoot->right,depth+1, data);
	}
};

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值