题意理解
锯齿形(Z字)层次遍历二叉树
问题分析
深度遍历二叉树的应用
思路是深度遍历,在输出树的元素时,结合深度和结果的格式选择好输出时机(遍历到同一层次再输出)和结果存放位置(这里是头插,还是尾插)。
其他
链接
vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
vector<vector<int>> res;
helper(root, res, 0); //改写成递归格式(补充遍历结果和遍历深度参数)
return res;
}
void helper(TreeNode* root, vector<vector<int>>& res, int depth)
{
if (!root) //子树不存在
return; //结束递归
if (res.size() <= depth) //结果层次数量不够
res.push_back({}); //增加层次结果
if (depth % 2 == 0) //深度是偶数
res[depth].push_back(root->val); //用尾插法
else
res[depth].insert(res[depth].begin(), root -> val); //奇数用前插法
helper(root -> left, res, depth + 1); //遍历左子树
helper(root -> right, res, depth + 1); //遍历右子树
}