标签:
题目:
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] ]
代码:
/** * 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) { std::vector<std::vector<int> > ret; if (!root) return ret; vector<int> tmp_ret; deque<TreeNode *> curr, next; bool left_2_right = true; curr.push_back(root); while ( !curr.empty() ) { while ( !curr.empty() ) { TreeNode *tmp = curr.front(); curr.pop_front(); tmp_ret.push_back(tmp->val); if ( tmp->left ) next.push_back(tmp->left); if ( tmp->right ) next.push_back(tmp->right); } if (!left_2_right) reverse(tmp_ret.begin(), tmp_ret.end()); ret.push_back(tmp_ret); tmp_ret.clear(); std::swap(curr, next); left_2_right = !left_2_right; } return ret; } };
tips:
隔层翻转顺序。加一个标志变量,判断是否从左往右。
注意,遍历的时候还是按照level order进行遍历,然后根据标志变量一层整体翻转一次。
【Binary Tree Zigzag Level Order Traversal】cpp
标签:
原文地址:http://www.cnblogs.com/xbf9xbf/p/4502844.html