Leetcode: Binary Tree Level Order Traversal II
原创
©著作权归作者所有:来自51CTO博客作者TheOneGIS的原创作品,请联系作者获取转载授权,否则将追究法律责任
题目:
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}
,
return its bottom-up level order traversal as:
分析:
这道题目跟上道题目很相似 Leetcode: Binary Tree Level Order Traversal ,唯一不同的就是返回结果是从子叶节点到根节点,所以我们只需要将结果翻转下就好了!
参考代码:
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution
{
private:
void visit(TreeNode *node, int depth, vector<vector<int>> &result)
{
if (node == NULL)
{
return;
}
if (result.size() > depth)
{
result[depth].push_back(node->val);
}
else
{
vector<int> level;
level.push_back(node->val);
result.push_back(level);
}
visit(node->left, depth + 1, result);
visit(node->right, depth + 1, result);
}
public:
vector<vector<int>> levelOrderBottom(TreeNode *root)
{
vector<vector<int>> result;
visit(root, 0, result);
//就只有最后一句不一样,返回值对vector做了一个reverse
return vector<vector<int>>(result.rbegin(), result.rend());
}
};