Binary Tree Level Order Traversal II

时间:2023-03-09 15:29:27
Binary Tree Level Order Traversal II
/**
* 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>> levelOrderBottom(TreeNode* root) {
vector<vector<int>> vv;
vector<int> v;
queue<TreeNode *>q;
if(root == NULL) return vv; q.push(root); int h0=;
int h1;
TreeNode * temp;
while(!q.empty()){
h1=;
while(h0){
temp= q.front();
q.pop();
v.push_back(temp->val); if(temp->left){
q.push(temp->left);
h1++;
}
if(temp->right){
q.push(temp->right);
h1++;
}
h0--;
}
vv.push_back(v);
v.clear(); h0=h1;
}
reverse(vv.begin(),vv.end());
return vv;
}
};