Binary tree level traversal ii binary-tree-level-order-traversal-ii
Title description
Given a binary tree, return the traversal of the binary tree from bottom to top, (from left to right, from leaf node to root node, traversal layer by layer)
For example:
the given binary tree is {3,9,20 ,#,#,15,7},
the result of traversing the binary tree from bottom to top level is
[
[15,7],
[9,20],
[3]
]
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},
return its bottom-up level order traversal as:
[
[15,7],
[9,20],
[3]
]
Problem-solving ideas
- Compared with the original hierarchical traversal, there is an additional requirement from the bottom to the top, so you only need to insert the nodes after each traversal to the beginning of the result (similar to the header interpolation) to achieve the reverse order.
- Insertion of vector:
vt.insert(vt.begin(), x);
insert element x at the beginning of
vt.insert(vt.begin() + 2, x);
vt insert element x at the third position of vt vt[2]
/**
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
class Solution {
public:
vector<vector<int> > levelOrderBottom(TreeNode* root) {
vector<vector<int> > res;
if(root == NULL) return res;
queue<TreeNode*> myque;
myque.push(root);
while(!myque.empty()) {
int size = myque.size();
vector<int> cur; //记录当前层的节点
for(int i = 0; i < size; i ++) {
TreeNode* temp = myque.front();
myque.pop();
cur.push_back(temp -> val);
if(temp -> left) myque.push(temp -> left);
if(temp -> right) myque.push(temp -> right);
}
//由于是底层到顶层,所以每次插入到开头
res.insert(res.begin(), cur);
}
return res;
}
};