Skip to content

Instantly share code, notes, and snippets.

@pdu
Created December 29, 2012 13:43
Show Gist options
  • Select an option

  • Save pdu/4407023 to your computer and use it in GitHub Desktop.

Select an option

Save pdu/4407023 to your computer and use it in GitHub Desktop.
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). http://www.leetcode.com/onlinejudge
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
void dfs(vector< vector<int> >& ret, int maxDepth, int curDepth, TreeNode* node) {
if (node == NULL) {
return;
}
dfs(ret, maxDepth, curDepth + 1, node->left);
dfs(ret, maxDepth, curDepth + 1, node->right);
ret[maxDepth - 1 - curDepth].push_back(node->val);
}
int getDepth(TreeNode* root) {
if (root == NULL) {
return 0;
}
else {
return 1 + max(getDepth(root->left), getDepth(root->right));
}
}
vector<vector<int> > levelOrderBottom(TreeNode *root) {
int maxDepth = getDepth(root);
vector< vector<int> > ret(maxDepth);
dfs(ret, maxDepth, 0, root);
return ret;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment