题解 | #求二叉树的层序遍历#
求二叉树的层序遍历
http://www.nowcoder.com/practice/04a5560e43e24e9db4595865dc9c63a3
class Solution { public: /** * * @param root TreeNode类 * @return int整型vector<vector<>> */ vector<vector<int> > levelOrder(TreeNode* root) { queue<TreeNode* > q; vector<vector<int> > result; if(root) q.push(root); while(!q.empty()) { int n=q.size(); vector<int> v; while(n--) { TreeNode* p=q.front(); q.pop(); v.push_back(p->val); if(p->left) q.push(p->left); if(p->right) q.push(p->right); } result.push_back(v); } return result; } };
注意考虑空树,