题目描述
给定一个二叉树,返回该二叉树层序遍历的结果,(从左到右,一层一层地遍历)
例如:
给定的二叉树是{3,9,20,#,#,15,7},
该二叉树层序遍历的结果是
[
[3],
[9,20],
[15,7]
]
代码如下:
1 vector<vector<int> > levelOrder(TreeNode* root) { 2 vector<vector<int>> res; 3 if(root == nullptr) 4 return res; 5 queue<TreeNode*> store; 6 TreeNode*node = nullptr; 7 vector<int> cur; 8 store.push(root); 9 while(!store.empty()) 10 { 11 cur.clear(); 12 int n = store.size(); 13 for(int i = 0;i < n;i++) 14 { 15 node = store.front(); 16 store.pop(); 17 cur.push_back(node->val); 18 if(node->left != nullptr) 19 store.push(node->left); 20 if(node->right != nullptr) 21 store.push(node->right); 22 } 23 res.push_back(cur); 24 } 25 return res; 26 }