题目
https://oj.leetcode.com/problems/binary-tree-level-order-traversal-ii/
分析
和Binary Tree Level Order Traversal一样, 只不过在最后把结果反转一下就行了。
代码
class Solution
{
public:
vector<vector<int>> levelOrderBottom(TreeNode *root)
{
queue<TreeNode*> nodeQue;
queue<int> depQue;
TreeNode *node;
int dep;
int depBefore;
vector<vector<int>> res;
vector<int> solution;
if (!root)
return res;
nodeQue.push(root);
depQue.push(1);
depBefore = 1;
while (!nodeQue.empty())
{
node = nodeQue.front();
nodeQue.pop();
dep = depQue.front();
depQue.pop();
if (dep == depBefore)
solution.push_back(node->val);
else
{
res.push_back(solution);
depBefore = dep;
solution.clear();
solution.push_back(node->val);
}
if (node->left)
{
nodeQue.push(node->left);
depQue.push(dep + 1);
}
if (node->right)
{
nodeQue.push(node->right);
depQue.push(dep + 1);
}
}
res.push_back(solution);
reverse(res.begin(), res.end());
return res;
}
};