题目链接:https://leetcode.com/problems/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,#,#,15,7}
,
3 / \ 9 20 / \ 15 7
return its bottom-up level order traversal as:
[ [15,7], [9,20], [3] ]
思路:和Binary Tree Level Order Traversal 几乎一样。
这是一个层次遍历,我们知道如果只是层次遍历的话可以用一个队列来保存节点,先入先出。现在我们还需要一个节点的处于第几层的信息, 和一个当前层数, 这样当我们发现当前队列中的结点和当前层数一样就放到当前数组中, 否则就将当前数组中的值存入结果集合中, 并且清空数组。
代码如下:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<vector<int>> levelOrder(TreeNode* root) {
vector<vector<int>> result;
if(!root) return result;
queue<TreeNode*> que;//结点队列
que.push(root);
queue<int> depth;//深度队列
depth.push(0);
vector<int> tem;
while(!que.empty())
{
TreeNode* node = que.front();
int curDepth = depth.front();
if(node->left)
{
que.push(node->left);
depth.push(depth.front()+1);
}
if(node->right)
{
que.push(node->right);
depth.push(curDepth+1);
}
depth.pop();
que.pop();
tem.push_back(node->val);
//如果队列空了或者当前的层数和下一个结点的层数不一样,则说明当前层已经遍历完了
if(depth.empty() || curDepth != depth.front())
{
result.push_back(tem);
tem.clear();
}
}
reverse(result.begin(), result.end());
return result;
}
};