leetcode | 107. 二叉树的层序遍历 II | javascript实现 | c++实现
题目
给你二叉树的根节点 root ,返回其节点值 自底向上的层序遍历 。 (即按从叶子节点所在层到根节点所在的层,逐层从左向右遍历)
思路
题目的要求相当于是求层序遍历数组的转置,我们只需利用js的unshift对返回数组进行头插法即可
代码
JavaScript实现
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @return {number[][]}
*/
var levelOrderBottom = function(root) {
let curLayer = 0; // 当前层节点数
let nextLayer = 0; // 下一层节点数
let layer = []; // 存储当前层节点列表
let queue = []; // 队列
let front; // 队头
let res = []; // 返回
if (root) {
queue.push(root);
curLayer++;
}
while (queue.length) {
front = queue.shift();
layer.push(front.val);
if (front.left) {
queue.push(front.left);
nextLayer++;
}
if (front.right) {
queue.push(front.right);
nextLayer++;
}
if (--curLayer === 0) {
curLayer = nextLayer;
nextLayer = 0;
res.unshift(layer);
layer = [];
}
}
return res;
};
c++
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
vector<vector<int>> levelOrderBottom(TreeNode* root) {
vector<int> layer;
queue<TreeNode*> q;
TreeNode* front;
vector<vector<int>> res;
int curLayer = 0;
int nextLayer = 0;
if (root) {
q.push(root);
curLayer++;
}
while (!q.empty()) {
front = q.front();
q.pop();
layer.push_back(front->val);
if (front->left) {
q.push(front->left);
nextLayer++;
}
if (front->right) {
q.push(front->right);
nextLayer++;
}
if (--curLayer == 0) {
curLayer = nextLayer;
nextLayer = 0;
res.push_back(layer);
layer.clear();
}
}
// reverse
int idx = res.size() - 1;
for (int k = 0; k < idx; k += 1, idx--) {
layer = res[idx];
res[idx] = res[k];
res[k] = layer;
}
return res;
}
};