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]
]
vector<vector<int>> levelOrderBottom(TreeNode* root) {
vector<vector<int>> res;
if (!root) {
return res;
}
queue<TreeNode*> t;
t.push(root);
while (!t.empty()) {
vector<int> tn;
int cnt = t.size();
for (unsigned int i = 0; i < cnt; ++i) {
TreeNode *cur = t.front();
tn.push_back(cur->val);
t.pop();
if (cur->left)
t.push(cur->left);
if (cur->right)
t.push(cur->right);
}
//do not use insert() here,it cost too much time.
//use reverse() insteadly
res.push_back(tn);
}
reverse(res.begin(), res.end());
return res;
}
REF: