给定一个二叉树,返回其节点值的锯齿形层次遍历。(即先从左往右,再从右往左进行下一层遍历,以此类推,层与层之间交替进行)。
例如:
给定二叉树 [3,9,20,null,null,15,7],
3
/
9 20
/
15 7
返回锯齿形层次遍历如下:
[
[3],
[20,9],
[15,7]
]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/binary-tree-zigzag-level-order-traversal
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
/**
* 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;
heads(root,0,res);
return res;
}
void heads(TreeNode *root,int depth,vector<vector<int>> &res)
{
if(!root) return;
if(depth>=res.size()) res.push_back(vector<int>{});//新增一行向量
if(depth%2==0) {
res[depth].push_back(root->val);//偶数照常插入
}
else
res[depth].insert(res[depth].begin(),root->val);//奇数在数组前进行插入
heads(root->left,depth+1,res);
heads(root->right,depth+1,res);
}
};