题目:
给定一个二叉树,返回其按层次遍历的节点值。 (即逐层地,从左到右访问所有节点)。
例如:
给定二叉树: [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回其层次遍历结果:
[
[3],
[9,20],
[15,7]
]
分析:
采用队列实现,队列中元素是当前结点和当前结点下标所在的层次,当取出队列中元素时,访问它并将它的左右孩子入队列(如果有的话),需要注意的是二维数组的大小得开够;直到队列为空为止。
class Solution {
public:
vector<vector<int>> levelOrder(TreeNode* root)
{
vector<vector<int>> res;//保存最终结果
queue<pair<TreeNode*, int>> tmp;//保存当前结点、当前结点层级
if (root)
tmp.push({root, 0});
int c;
while (!tmp.empty())
{
TreeNode* p = tmp.front().first;//队首结点
c = tmp.front().second;//队首结点的层级
//一位数组先得存在
if (res.size() < c + 1)
res.push_back({});
res[c].push_back(p->val);//将队首结点值入到属于它的这一层(下标是c)
tmp.pop();//队首结点出队
if (p->left) //队首结点的左孩子入栈
tmp.push({p->left, c + 1});
if (p->right) //队首结点的右孩子入栈
tmp.push({p->right, c + 1});
}
return res;
}
};