LeetCode() Binary Tree Level Order Traversal

感觉我这个思路好 先记录上一层有几个节点

/**
* 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:
vector<vector<int>> levelOrder(TreeNode* root) {
vector<vector<int>> res;
vector<int> path;
queue<TreeNode*> q;
if(!root) return res;
q.push(root);
while(!q.empty()){
int len=q.size();
while(len--){
TreeNode* tem=q.front();
q.pop();
path.push_back(tem->val); if(tem->left!=NULL) q.push(tem->left);
if(tem->right!=NULL) q.push(tem->right);
}
res.push_back(path);
path.clear();
}
return res;
}
};

  

上一篇:Web应用开发工具及语言需要具备的功能探索


下一篇:js识别用户设备是移动端手机时跳转到手机网站