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.
与层次遍历一样,不够要添加一个行数标记,如果是偶数行,将层次遍历获取的行vector<int>反转一下就可以
vector<vector<int> > zigzagLevelOrder(TreeNode *root){ vector<vector<int> > result; if(root == NULL) return result; queue<TreeNode *> que; que.push(root); int cnt = 1,rowline = 1; while(!que.empty()){ vector<int> row; int newCnt = 0; while(cnt--){ TreeNode *node = que.front();que.pop(); row.push_back(node->val); if(node->left) {que.push(node->left); newCnt++;} if(node->right) {que.push(node->right); newCnt++;} } cnt = newCnt; if(rowline%2 == 0) reverse(row.begin(),row.end()); result.push_back(row); rowline++; } return result; }