Leetcode102.Binary_Tree_Level_Order_Traversal

用队列对二叉树进行层次遍历,因为需要把不同层的元素储存在不同的数组里,所以要额外保存数据在哪一层上。
不要用整型数据判断数据读取到哪层上(本人开始时用第n层有 2 n 2^n 个节点(储存目前加进数组的个数和因上面若干节点为空导致本层节点缺失的个数)判断目前数据在哪层),这种储存方式虽然空间占用少,但当n过大时数据会溢出(有一测试用例有600层)。

class Solution {
public:
	vector<vector<int>> levelOrder(TreeNode* root) 
	{
		if (root == nullptr)
			return {};
		vector<vector<int>> result;
		queue<pair<TreeNode*,int>> record;
		record.push(make_pair(root, 1));
		while (!record.empty())
		{
			auto now = record.front();
			record.pop();
			if (result.size() < now.second)
				result.push_back({});
			result[now.second - 1].push_back(now.first->val);
			if (now.first->left != nullptr)
				record.push(make_pair(now.first->left, now.second + 1));
			if (now.first->right != nullptr)
				record.push(make_pair(now.first->right, now.second + 1));
		}
		return result;
	}
};

猜你喜欢

转载自blog.csdn.net/qq_42263831/article/details/83825697