【Binary Tree Zigzag Level Order Traversal】cpp
题目:
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进行遍历,然后根据标志变量一层整体翻转一次。
============================================
第二次过这道题,设置标志变量就跟level traversal一样了。
/** * 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> > ret; bool right2left = false; queue<TreeNode*> curr; queue<TreeNode*> next; if ( root ) curr.push(root); while ( !curr.empty() ) { vector<int> level; while ( !curr.empty() ) { TreeNode* tmp = curr.front(); curr.pop(); level.push_back(tmp->val); if ( tmp->left ) next.push(tmp->left); if ( tmp->right ) next.push(tmp->right); } if ( right2left ) std::reverse(level.begin(), level.end()); right2left = !right2left; ret.push_back(level); std::swap(next, curr); } return ret; } };