Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xiren-wang/02027cd0c3d1b2f84d83 to your computer and use it in GitHub Desktop.
Save xiren-wang/02027cd0c3d1b2f84d83 to your computer and use it in GitHub Desktop.
binary tree level order traversal II.
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
* 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]
]
*/
class Solution {
public:
vector<vector<int> > levelOrderBottom(TreeNode *root) {
//two queue to hold parents and their children
// if parentQ is empty, one level is done; record all int at this levle
//
// Final, reverse order of vvInt
vector<vector<int> >vvInt;
vector<int> vInt;
queue<TreeNode *> parentQ;
if (root)
parentQ.push(root);
queue<TreeNode *> childQ;
while (!parentQ.empty()) {
TreeNode *aNode = parentQ.front();
parentQ.pop();
vInt.push_back(aNode->val);
if (aNode->left)
childQ.push(aNode->left);
if (aNode->right)
childQ.push(aNode->right);
if (parentQ.empty()) {
swap(parentQ, childQ);
vvInt.push_back(vInt);
vInt.clear();
}
}
//reverse the order of vvInt;
int size = vvInt.size();
int half = size/2;
for(int i=0; i<half; i++)
swap(vvInt[i], vvInt[size-1-i]);
return vvInt;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment