给定一个二叉树,返回其节点值的锯齿形层次遍历。(即先从左往右,再从右往左进行下一层遍历,以此类推,层与层之间交替进行)。
例如:
给定二叉树 [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回锯齿形层次遍历如下:
[
[3],
[20,9],
[15,7]
]
详见:https://leetcode.com/problems/binary-tree-zigzag-level-order-traversal/description/
/** * 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>> res; if(!root) { return res; } queue<TreeNode*> que; que.push(root); int i=1; bool flag=true; vector<int> out; while(!que.empty()) { root=que.front(); que.pop(); --i; if(root->left) { que.push(root->left); } if(root->right) { que.push(root->right); } if(flag) { out.push_back(root->val); } else { out.insert(out.begin(),root->val); } if(i==0) { i=que.size(); res.push_back(out); flag=!flag; out.clear(); } } return res; } };