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] ]
基本思路:
1. 使用广度优先搜索
2. 交替使用两个栈。一个表示当前层,一个表示下一层的节点。
3. 使用一个标志变量,表示该层中,先入左节点,还是先入右结点。
在leetcode上实际执行时间为4ms。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
vector<vector<int> > ans;
if (!root) return ans;
stack<TreeNode *> *next = new stack<TreeNode *>();
stack<TreeNode *> *curr = new stack<TreeNode *>();
curr->push(root);
bool flag = true;
while (!curr->empty()) {
ans.push_back(vector<int>());
ans.back().reserve(curr->size());
while (!curr->empty()) {
root = curr->top();
curr->pop();
ans.back().push_back(root->val);
if (flag) {
if (root->left) next->push(root->left);
if (root->right) next->push(root->right);
}
else {
if (root->right) next->push(root->right);
if (root->left) next->push(root->left);
}
}
swap(next, curr);
flag = !flag;
}
delete next;
delete curr;
return ans;
}
};Binary Tree Zigzag Level Order Traversal -- leetcode
原文地址:http://blog.csdn.net/elton_xiao/article/details/45537385