标签:tree breadth-first-search stack leetcode
题目:
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] ]
confused what "{1,#,2,3}"
means? >
read more on how binary tree is serialized on OJ.
思路:这道题的解法和思路和Binary Tree Level Order Traversal差不多,只不过我们需要设个标志位来区分,这行是正序还是反序输出数组。我们利用队列来存储树的节点,并用NULL来区分每一行,记得当队列非空时,处理完每一行,都需要清空level数组,并加入NULL,区别下一行。我们设置tag, tag为True,表示正序,从左到右输出数组,tag为false, 表示反序,从右往左输出数组。
Attention:
1. 记得处理完每一行后,当队列非空时,清空数组level, 并且往队列中加入NULL,区分下一行。
2. reverse的用法
void reverse (BidirectionalIterator first, BidirectionalIterator last);
std::reverse(myvector.begin(),myvector.end());
3. 用tag来区分输出顺序。记得每次都需要tag取反,下次是反方向。
if(tag) { ret.push_back(level); } else { reverse(level.begin(), level.end()); ret.push_back(level); } tag = !tag;
复杂度:O(N),N为树的节点个数。
AC Code:
/** * Definition for binary tree * 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; if(root == NULL) return ret; vector<int> level; bool tag = true; queue<TreeNode*> TreeQ; TreeQ.push(root); TreeQ.push(NULL); //区分分层 while(!TreeQ.empty()) { TreeNode* node = TreeQ.front(); TreeQ.pop(); if(node != NULL) { level.push_back(node->val); if(node->left) TreeQ.push(node->left); if(node->right) TreeQ.push(node->right); } else { if(tag) { ret.push_back(level); } else { reverse(level.begin(), level.end()); ret.push_back(level); } tag = !tag; if(!TreeQ.empty()) { level.clear(); TreeQ.push(NULL); } } } return ret; } };
[C++]LeetCode: 101 Binary Tree Zigzag Level Order Traversal
标签:tree breadth-first-search stack leetcode
原文地址:http://blog.csdn.net/cinderella_niu/article/details/42778315