【LeetCode】107. 二叉树的层次遍历 II
LeetCode:https://leetcode-cn.com/problems/binary-tree-level-order-traversal-ii/
给定一个二叉树,返回其节点值自底向上的层次遍历。 (即按从叶子节点所在层到根节点所在的层,逐层从左向右遍历)
例如:
给定二叉树 [3,9,20,null,null,15,7]
,
3 / \ 9 20 / \ 15 7
返回其自底向上的层次遍历为:
[ [15,7], [9,20], [3] ]
思路:
在【LeetCode】102. 二叉树的层次遍历的基础上,在准备返回最终结果前,用vector模板函数的翻转函数reverse()对vector进行翻转,即可得到最终所求。
/**
* 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:
int TreeHeight(TreeNode* root)
{
if(!root)
return 0;
int lefth = TreeHeight(root->left);
int righth = TreeHeight(root->right);
return lefth > righth ? lefth + 1 : righth + 1;
}
vector<vector<int>> levelOrderBottom(TreeNode* root) {
queue<TreeNode*> nodeq;
queue<int> levelq;
vector<vector<int>> v;
if(root)
{
nodeq.push(root);
levelq.push(1);
}
v.resize(TreeHeight(root));
while(!nodeq.empty())
{
TreeNode* node = nodeq.front();
nodeq.pop();
int level = levelq.front();
levelq.pop();
v[level - 1].push_back(node->val);
if(node->left)
{
nodeq.push(node->left);
levelq.push(level+1);
}
if(node->right)
{
nodeq.push(node->right);
levelq.push(level+1);
}
}
reverse(v.begin(),v.end());
return v;
}
};