Created
December 29, 2012 13:43
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * 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