一. 題目描述
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
二. 題目分析
由於使用了vector,這一題只需Binary Tree Level Order Traversal的基礎上加一句reverse(result.begin(), result.end()) 即可。印象中編程之美上有這題。
三. 示例代碼
#include
#include
using namespace std;
struct TreeNode
{
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) :val(x), left(NULL), right(NULL){}
};
class Solution
{
public:
vector > levelOrderBottom(TreeNode *root)
{
vector > result;
orderTraversal(root, 1, result);
reverse(result.begin(), result.end()); // 新增
return result;
}
private:
void orderTraversal(TreeNode *root, size_t level, vector > & result)
{
if (root == NULL) return;
if (level > result.size())
result.push_back(vector());
result[level - 1].push_back(root->val);
orderTraversal(root->left, level + 1, result);
orderTraversal(root->right, level + 1, result);
}
};
四. 小結
解法同Binary Tree Level Order Traversal,同樣有多種解法,還需認真研究。