树和二叉树_9
- 一、leetcode-107
- 二、题解
- 1.引库
- 2.代码
一、leetcode-107
二叉树的层序遍历Ⅱ
给你二叉树的根节点 root ,返回其节点值 自底向上的层序遍历 。 (即按从叶子节点所在层到根节点所在的层,逐层从左向右遍历)。
样例输入:root = [3,9,20,null,null,15,7]
样例输出: [[15,7],[9,20],[3]]
二、题解
1.引库
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <queue>
#include <stack>
#include <algorithm>
#include <string>
#include <map>
#include <set>
#include <vector>
using namespace std;
2.代码
/**
* 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:
void dfs(TreeNode *root,int k,vector<vector<int>> &ans){
if(root==NULL) return ;
if(k==ans.size()) ans.push_back(vector<int>());
ans[k].push_back(root->val);
dfs(root->left, k+1,ans);
dfs(root->right,k+1,ans);
return ;
}
vector<vector<int>> levelOrderBottom(TreeNode* root) {
vector<vector<int>> ans;
dfs(root,0,ans);
for(int i=0,j=ans.size()-1;i<j;i++,j--){
swap(ans[i],ans[j]);
}
return ans;
}
};