题意理解
二叉树层次遍历
问题分析
层次遍历的结果是一个二维数组,每一层元素作为一个子数组。
思路:递归思想,函数参数三个,返回层次遍历的二维数组结果, 二叉树根节点 和 当前深度depth。遍历方法,如果子树为空,遍历结果为空,如果结果长度等于深度,说明是新的层次,增加一个空数组;否则,给对应深度的数组增加当前元素,然后分别递归调用左右子树,深度加1。
其他
层次遍历,常规思路是用队列,这题不同的地方在于要标注层次遍历的层次信息。这题的思路是用了中序遍历的递归算法,在递归算法的输入参数和结果输出上做了文章。学习。
好思路。
相同思路的题还有103. Binary Tree Zigzag Level Order Traversal,变化的是层次遍历完后对于奇数行作一次翻转reverse即可。
初始化vector用vector<int>{},前面不带new。
链接
vector<vector<int>> levelOrder(TreeNode* root) {
vector<vector<int>> res;
helper(res, root, 0);
return res;
}
void helper(vector<vector<int>>& res, TreeNode* root, int depth)
{
if(!root) //空树,直接返回
return;
if (res.size() <= depth) // 深度大于层数
{
res.push_back(vector<int>{}); //扩展新层
}
res[depth].push_back(root -> val); // 当前层增加根元素
helper(res, root -> left, depth + 1); //深度遍历左子树
helper(res, root -> right, depth + 1); //深度遍历右子树
}