一. 題目描述
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
二. 題目分析
BFS,這裡用一個bool記錄是從左到右還是從右到左讀取數據,每一層遍歷結束就翻轉一下。
三. 示例代碼
#include
#include
using namespace std;
struct TreeNode
{
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) :val(x), left(NULL), right(NULL){}
};
class Solution
{
public:
vector > zigzagLevelOrder(TreeNode *root)
{
vector > result;
Traverse(root, 1, result, true);
return result;
}
private:
void Traverse(TreeNode *root, size_t level, vector > & result, bool leftToRight)
{
if (root == NULL) return;
if (level > result.size())
result.push_back(vector());
if (leftToRight)
result[level - 1].push_back(root->val);
else
result[level - 1].insert(result[level - 1].begin(), root->val);
Traverse(root->left, level + 1, result, !leftToRight);
Traverse(root->right, level + 1, result, !leftToRight);
}
};
四. 小結
比Binary Tree Level Order Traversal 和Binary Tree Level Order Traversal II 稍微難一些,需要注意更多細節。