107.Binary Tree Level Order Traversal II¶
Tags: Easy
Tree
Link: 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,null,null,15,7]
,
3
/ \
9 20
/ \
15 7
return its bottom-up level order traversal as:
[
[15,7],
[9,20],
[3]
]
Answer:
/**
* 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:
//迭代法,时间复杂度O(n),空间复杂度O(1)
vector<vector<int>> levelOrderBottom(TreeNode* root) {
vector<vector<int>> result;
if(root == nullptr) return result;
queue<TreeNode *> cur;
cur.push(root);
while(!cur.empty()){
vector<int> tmp;
for(int i = cur.size(); i > 0; --i){
TreeNode *p = cur.front();
cur.pop();
tmp.push_back(p -> val);
if(p -> left != nullptr) cur.push(p -> left);
if(p -> right != nullptr) cur.push(p -> right);
}
result.push_back(tmp);
}
reverse(result.begin(),result.end()); //相比于102多了这一行
return result;
}
};