标签:alt tor 需要 img 结构体 return back com struct
leetcode - 102:https://leetcode-cn.com/problems/binary-tree-level-order-traversal/
这道题可以不用结构体,在while循环里面加一个for循环来遍历某一层的节点。但是很多宽搜的题一般节点需要存储一些别的信息,所以我写BFS基本都统一用结构体来做了。
/**
* 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:
// 新定义一个结构体,存储节点的高度和节点
struct FloorNode {
TreeNode *node;
int depth;
FloorNode(int _depth, TreeNode* _node){
depth = _depth;
node = _node;
}
};
vector<vector<int>> levelOrder(TreeNode* root) {
vector<vector<int>> ans;
if(root==NULL) return ans;
queue<FloorNode> Q;
Q.push(FloorNode(0,root));
ans.push_back(vector<int>());
int depth = 0;
while(!Q.empty()){
FloorNode tmp = Q.front();
TreeNode* tmpNode = tmp.node;
Q.pop();
if(depth!=tmp.depth){
ans.push_back(vector<int>());
depth++;
}
ans[depth].push_back(tmpNode->val);
if(tmpNode->left){
Q.push(FloorNode(depth+1,tmpNode->left));
}
if(tmpNode->right){
Q.push(FloorNode(depth+1,tmpNode->right));
}
}
return ans;
}
};
标签:alt tor 需要 img 结构体 return back com struct
原文地址:https://www.cnblogs.com/baboon/p/13160722.html