题目:
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] ]
代码:
/** * 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> > ret; if (!root) return ret; vector<int> tmp_ret; deque<TreeNode *> currLevel, nextLevel; currLevel.push_back(root); while ( !currLevel.empty() ) { while ( !currLevel.empty() ) { TreeNode * tmp = currLevel.front(); currLevel.pop_front(); tmp_ret.push_back(tmp->val); if ( tmp->left ) nextLevel.push_back(tmp->left); if ( tmp->right ) nextLevel.push_back(tmp->right); } ret.push_back(tmp_ret); tmp_ret.clear(); std::swap(currLevel, nextLevel); } std::reverse(ret.begin(), ret.end()); return ret; } };
tips:
在Binary Tree Level Order Traversal的基础上加一个reverse即可。
时间: 2024-10-15 21:10:56