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] ]
题目解析:
将层序遍历的结果反向输出,就是从最深层,向最顶层输出。
很简单,当层序遍历完后,将最后的res反向即可。没难度。
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
struct Node
{
TreeNode *node;
int level;
Node(){}
Node(TreeNode *n, int l):node(n), level(l){}
};
class Solution {
private:
vector<vector<int> > ret;
vector<vector<int> > retReverse;
public:
vector<vector<int> > levelOrder(TreeNode *root) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
ret.clear();
if (root == NULL)
return ret;
queue<Node> q;
q.push(Node(root, 0));
vector<int> a;
int curLevel = -1;
while(!q.empty())
{
Node node = q.front();
if (node.node->left)
q.push(Node(node.node->left, node.level + 1));
if (node.node->right)
q.push(Node(node.node->right, node.level + 1));
if (curLevel != node.level)
{
if (curLevel != -1)
ret.push_back(a);
curLevel = node.level;
a.clear();
a.push_back(node.node->val);
}
else
a.push_back(node.node->val);
q.pop();
}
ret.push_back(a);
retReverse.clear();
for(int i = ret.size() - 1; i >= 0; i--)
retReverse.push_back(ret[i]);
return retReverse;
}
};