107. Binary Tree Level Order Traversal II
一、问题描述
Given a binary tree, return the bottom-up level order traversal of its nodes’ values. (ie, from left to right, level by level from leaf to root).
二、输入输出
For example: Given binary tree [3,9,20,null,null,15,7],
3
/
\
9 20
/
\
15 7
return its bottom-up level order traversal as:
[
[
15,
7],
[
9,
20],
[
3]
]
三、解题思路
二叉树-层次遍历
非常典型的二叉树的层次遍历。其实就是广度优先搜索 + queue 和广度优先搜索稍微不同的是,在层次遍历中需要记录下三个参数:当前层次的总个数,当前层次遍历的个数,下一层的节点个数。最初的时候,只把root入队即可。题目要求是从叶节点到根节点,所以ret是在begin的位置进行插入的。
class Solution {
public:
vector<vector<int>> levelOrderBottom(TreeNode* root) {
vector<vector<int>> ret;
if(root ==
nullptr)
return ret;
queue<TreeNode *> q;
q.push(root);
int currLevelCount =
1;
int nextLevelCount =
0;
int count =
0;
vector<int> each;
while(!q.empty())
{
TreeNode* head = q.front();q.pop();
count++;
each.emplace_back(head->val);
if(head->left){
nextLevelCount++;
q.push(head->left);
}
if(head->right){
nextLevelCount++;
q.push(head->right);
}
if(count == currLevelCount){
count =
0;
currLevelCount = nextLevelCount;
nextLevelCount =
0;
ret.insert(ret.begin(),each);
each.clear();
}
}
return ret;
}
};