题意:

层次遍历树,一行从左向右,一行从右向左。

思路:

和之前普通层次遍历相仿,但将每层存于vector改为list,因为list倒序遍历较快。用一个flag控制每行的方向。


struct Node {
	TreeNode *TN;
	int L;
	Node(TreeNode *t, int i) :TN(t), L(i) {};
};

vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
	if (!root)
		return vector<vector<int>>();
	list<Node> li;
	Node p = Node(root, 0);
	li.push_back(p);
	int lv = 0;
	vector<vector<int>> res;

	list<int> curl;
	bool flag = 0;
	while (!li.empty()) {
		p = li.front();
		li.pop_front();
		if (p.L != lv) {
			if (flag)
				res.push_back(vector<int>(curl.rbegin(),curl.rend()));
			else
				res.push_back(vector<int>(curl.begin(), curl.end()));
			curl.clear();
			lv++;
			flag = !flag;
		}
		curl.push_back(p.TN->val);
		if (p.TN->left)
			li.push_back(Node(p.TN->left, lv + 1));
		if (p.TN->right)
			li.push_back(Node(p.TN->right, lv + 1));
	}
	if (flag)
		res.push_back(vector<int>(curl.rbegin(), curl.rend()));
	else
		res.push_back(vector<int>(curl.begin(), curl.end()));
	return res;
}