leetcode 103. Binary Tree Zigzag Level Order Traversal

Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from left to right, then right to left for the next level and alternate between).

For example:
Given binary tree {3,9,20,#,#,15,7},

    3
   / \
  9  20
    /  \
   15   7

return its zigzag level order traversal as:

[
  [3],
  [20,9],
  [15,7]
]


class Solution {
public:
	vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
		vector<vector<int>>re;
		if (root == NULL)
			return re;
		vector<TreeNode*>que;
		que.push_back(root);
		vector<int>aa; aa.push_back(root->val); re.push_back(aa);
		bool left2right = false;
		while (!que.empty())
		{
			vector<TreeNode*>newque;
			for (int i = 0; i < que.size(); i++)
			{
				if (que[i]->left != NULL)
					newque.push_back(que[i]->left);
				if (que[i]->right != NULL)
					newque.push_back(que[i]->right);
			}
			if (left2right)
			{
				if (!newque.empty())
				{
					vector<int>bb;
					for (int i = 0; i < newque.size(); i++)
						bb.push_back(newque[i]->val);
					re.push_back(bb);
				}
			}
			else
			{
				if (!newque.empty())
				{
					vector<int>bb;
					for (int i = newque.size()-1; i >=0; i--)
						bb.push_back(newque[i]->val);
					re.push_back(bb);
				}
			}
			left2right = !left2right;
			que = newque;
		}
		return re;
	}
};


你可能感兴趣的:(LeetCode)