树和二叉树_7
- 一、leetcode-102
- 二、题解
- 1.引库
- 2.代码
一、leetcode-102
二叉树的层序遍历
给你二叉树的根节点 root ,返回其节点值的 层序遍历 。 (即逐层地,从左到右访问所有节点)。
样例输入:root = [3,9,20,null,null,15,7]
样例输出: [[3],[9,20],[15,7]]
二、题解
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:
//使用队列进行广度搜索实现层序遍历
vector<vector<int>> levelOrder(TreeNode* root) {
if(root==NULL) return vector<vector<int>>();
TreeNode *node;
queue<TreeNode *> q;
q.push(root);
vector<vector<int>> ans;
while(!q.empty()){
int cnt=q.size();
vector<int> temp;
for(int i=0;i<cnt;i++){
node=q.front();
temp.push_back(node->val);
if(node->left) q.push(node->left);
if(node->right) q.push(node->right);
q.pop();
}
ans.push_back(temp);
}
return ans;
}
//使用栈进行深度搜索实现层序遍历
void dfs(TreeNode* root,int k,vector<vector<int>> &ans){
if(root==NULL) return ;
if(k==ans.size()) ans.push_back(vector<int>());//如果k=数组的数量,说明是本层中第一个访问到的节点
ans[k].push_back(root->val);
dfs(root->left, k+1,ans);
dfs(root->right, k+1,ans);
return ;
}
vector<vector<int>> levelOrder(TreeNode* root) {
vector<vector<int>> ans;
dfs(root,0,ans); //0是树的层数
return ans;
}
};