102. 二叉树的层序遍历
有两种实现方法。第一种是递归,第二种是队列实现。第一种是看了别人的代码写出来的,第二种是自己写的。这道题的不能直接把遍历得到的数字直接塞进res里,需要区分不同的层次。所以返回的是二维vector
递归
index用来表示这是第几层,要放到哪一个一维数组
class Solution { public: vector<vector<int>> res; void Tracking(TreeNode* root,int index) { if(root==nullptr) return; if(index>=res.size()) { res.push_back(vector<int>()); } res[index].push_back(root->val); Tracking(root->left,index+1); Tracking(root->right,index+1); } vector<vector<int>> levelOrder(TreeNode* root) { if(root==nullptr) return {}; Tracking(root,0); return res; } };
层序遍历队列实现没什么好说的,但是第一次写的代码用while循环忘记size--,就一直显示显示runtime error: member access within misaligned address 0xbebebebebebebebe for type 'TreeNode'错误,看了很久都看不出来。
/** * 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==nullptr) return {}; queue<TreeNode*> sss; vector<vector<int>> res; sss.push(root); while(!sss.empty()) { int size=sss.size(); vector<int> temp; for(int i=0;i<size;i++) { TreeNode *t=sss.front(); sss.pop(); temp.push_back(t->val); if(t->left) sss.push(t->left); if(t->right) sss.push(t->right); } res.push_back(temp); } return res; /*queue<TreeNode*> sss; vector<vector<int>> res; if(root!=nullptr) sss.push(root); while(!sss.empty()) { int size=sss.size(); vector<int> temp; while(size>0) { TreeNode* t=sss.front(); sss.pop(); temp.push_back(t->val);//这里标了红色波浪线 if(t->left) sss.push(t->left); if(t->right) sss.push(t->right); size--; } res.push_back(temp); } return res;*/ } };
标签:right,TreeNode,res,层序,sss,二叉树,leetcode102,push,root From: https://www.cnblogs.com/uacs2024/p/16840721.html