我的方法。每个队列保存一层的node:
/** * 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; queue<TreeNode*> qu; if(!root){ return res; } qu.push(root); soln(res,qu); return res; } void soln(vector<vector<int>>& res, queue<TreeNode*>& qu1){ if(qu1.empty()){ return; } queue<TreeNode*> qu2; vector<int> tem; while(!qu1.empty()){ tem.push_back(qu1.front()->val); if(qu1.front()->left){ qu2.push(qu1.front()->left); } if(qu1.front()->right){ qu2.push(qu1.front()->right); } qu1.pop(); } res.push_back(tem); soln(res,qu2); } };
8ms 。
可以用递归。
为什么非得一层加完了再加下一层呢?没有必要。
class Solution { private: vector<vector<int>>res; public: void levelOrder(struct TreeNode* root,int level){ if(root==NULL)return ; if(level==res.size()){ vector<int> v; res.push_back(v); } res[level].push_back(root->val); levelOrder(root->left,level+1); levelOrder(root->right,level+1); } vector<vector<int>> levelOrder(TreeNode* root) { levelOrder(root,0); return res; } };
4ms。
只用一个队列,来自leetcode。
class Solution { public: vector<vector<int>> levelOrder(TreeNode* root) { if (root == nullptr) return vector<vector<int>>{}; vector<vector<int>> res; vector<int> row; TreeNode *last, *pre_last = root, *cur = root; queue<TreeNode*> nodes; nodes.push(cur); while (!nodes.empty()) { cur = nodes.front(); row.push_back(cur->val); if (cur->left) { nodes.push(cur->left); last = cur->left; } if (cur->right) { nodes.push(cur->right); last = cur->right; } if (cur == pre_last) { res.push_back(row); row.clear(); pre_last = last; } nodes.pop(); } return res; } };
4ms。