107. Binary Tree Level Order Traversal II
欢迎fork and star:Nowcoder-Repository-github
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]
]
解析
- 题目虽然思路很清晰,但是查看了方法2,3感觉也吸收了很多思路!
// Binary Tree Level Order Traversal II
class Solution_107 {
public:
//bfs
vector<vector<int>> levelOrderBottom(TreeNode* root) {
vector<vector<int> > vecs;
stack<vector<int>> sta;
if (!root)
{
return vecs;
}
queue<TreeNode*> que;
que.push(root);
while (!que.empty())
{
int size = que.size();
vector<int> vec;
TreeNode* temp;
for (int i = 0; i < size;i++)
{
temp = que.front();
que.pop();
vec.push_back(temp->val);
if (temp->left)
{
que.push(temp->left);
}
if (temp->right)
{
que.push(temp->right);
}
}
sta.push(vec);
}
// reverse(res.begin(),res.end());
while (!sta.empty())
{
vector<int> vec = sta.top();
sta.pop();
vecs.push_back(vec);
}
return vecs;
}
// 记录每层的个数;curCount当前层个数,nextCount下一层个节点个数
vector<vector<int>> levelOrderBottom1(TreeNode* root) {
int curCount = 0, nextCount = 0, level = 0;
vector<vector<int>> ret;
if (!root) return ret;
curCount = 1;
queue<TreeNode*> q;
q.push(root);
ret.push_back(vector<int>(0, curCount));
while (!q.empty()) {
if (curCount == 0) {
curCount = nextCount;
nextCount = 0;
level++;
ret.push_back(vector<int>(0, curCount)); //初始化下一层vector的大小
}
TreeNode *node = q.front();
q.pop();
curCount--;
ret[level].push_back(node->val); //在同一层的节点加入
if (node->left) {
nextCount++;
q.push(node->left);
}
if (node->right) {
nextCount++;
q.push(node->right);
}
}
reverse(ret.begin(), ret.end());
return ret;
}
//dfs
int getHeight(TreeNode *root)
{
if (!root)
return 0;
return max(getHeight(root->left), getHeight(root->right)) + 1;
}
vector<vector<int> > levelOrderBottom2(TreeNode *root)
{
if (!root)
return vector<vector<int>>();
vector<vector<int>> res(getHeight(root), vector<int>());
dfs(root, res.size() - 1, res);
return res;
}
void dfs(TreeNode *root, int height, vector<vector<int>> &res)
{
if (!root)
return;
res[height].push_back(root->val);
dfs(root->left, height - 1, res);
dfs(root->right, height - 1, res);
}
};
题目来源
C/C++基本语法学习
STL
C++ primer