题目来源
力扣429N叉树的层序遍历
题目概述
给定一个 N 叉树,返回其节点值的层序遍历。(即从左到右,逐层遍历)。
思路分析
跟二叉树的层序遍历基本一致,只不过把向孩子节点列表添加左右节点该成了添加父节点的全部孩子节点。
代码实现
java实现
public class Solution {public List<List<Integer>> levelOrder(Node root) {// 结果列表List<List<Integer>> res = new ArrayList<>();// 父节点列表List<Node> parentList = new ArrayList<>();parentList.add(root);while (!parentList.isEmpty()) {// 本轮父节点转valList<Integer> temp = new ArrayList<>();// 孩子节点列表List<Node> sonList = new ArrayList<>();for (Node parent : parentList) {temp.add(parent.val);if (parent.children != null && parent.children.size() > 0) {sonList.addAll(parent.children);}}res.add(temp);parentList = sonList;}return res;}
}
c++实现
class Solution {
public:vector<vector<int>> levelOrder(Node* root) {// 结果列表vector<vector<int>> res;if (root == nullptr) {return res;}// 父节点列表vector<Node*> parent_list;parent_list.push_back(root);while (!parent_list.empty()){// 父节点转valvector<int> temp;// 孩子节点列表vector<Node*> son_list;for (auto parent : parent_list) {temp.push_back(parent->val);for (auto child : parent->children) {son_list.push_back(child);}}parent_list = son_list;res.push_back(temp);}return res;}
}