Leetcode C++《热题 Hot 100-44》102.二叉树的层次遍历
- 题目
给定一个二叉树,返回其按层次遍历的节点值。 (即逐层地,从左到右访问所有节点)。
例如:
给定二叉树: [3,9,20,null,null,15,7],
3
/
9 20
/
15 7
返回其层次遍历结果:
[
[3],
[9,20],
[15,7]
]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/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;
if (root == NULL)
return res;
vector<TreeNode*> oneLine;
vector<TreeNode*> childrens;
oneLine.push_back(root);
vector<int> oneres;
while(!oneLine.empty()) {
oneres.clear();
childrens.clear();
for (int i = 0; i < oneLine.size(); i++) {
if (oneLine[i]->left!=NULL)
childrens.push_back(oneLine[i]->left);
if (oneLine[i]->right!=NULL)
childrens.push_back(oneLine[i]->right);
oneres.push_back(oneLine[i]->val);
}
res.push_back(oneres);
oneLine.assign(childrens.begin(), childrens.end());
}
return res;
}
};