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; }