Binary Tree Level Order Traversal II
最后更新于:2022-04-01 22:56:44
**一. 题目描述**
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,同样有多种解法,还需认真研究。
';