一. 题目描述
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 <iostream>
#include <vector>
using namespace std;
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> > result;
orderTraversal(root, 1, result);
reverse(result.begin(), result.end()); // 新增
return result;
}
private:
void orderTraversal(TreeNode *root, size_t level, vector<vector<int> > & result)
{
if (root == NULL) return;
if (level > result.size())
result.push_back(vector<int>());
result[level - 1].push_back(root->val);
orderTraversal(root->left, level + 1, result);
orderTraversal(root->right, level + 1, result);
}
};
四. 小结
解法同Binary Tree Level Order Traversal,同样有多种解法,还需认真研究。
版权声明:本文为博主原创文章,未经博主允许不得转载。
时间: 2024-10-21 19:10:13