給定一個二叉樹,返回其節點值的鋸齒形層次遍歷。(即先從左往右,再從右往左進行下一層遍歷,以此類推,層與層之間交替進行)。
例如:
給定二叉樹?[3,9,20,null,null,15,7],? ? 3
? ?/ \
? 9 ?20
? ? / ?\
? ?15 ? 7
返回鋸齒形層次遍歷如下:[
? [3],
? [20,9],
? [15,7]
]
解法:
class Solution {
public:vector<vector<int>> zigzagLevelOrder(TreeNode* root) {if(!root) return {};vector<vector<int>> res;queue<TreeNode *> qu;qu.push(root);int n = 0;while(!qu.empty()){int count = qu.size();vector<int> curr;while(count--){TreeNode *s = qu.front();qu.pop();curr.push_back(s->val);if(s->left) qu.push(s->left);if(s->right) qu.push(s->right);}++n;if(n % 2 == 0)std::reverse(curr.begin(), curr.end());res.push_back(curr);}return res;}
};
?