C++ 中的 N 叉树层序遍历


假设我们有一个 n 叉树,我们需要返回其节点值的层序遍历。N 叉树输入序列化以其层序遍历表示。此处,每组子节点以空值分隔(请参见示例)。因此,以下树可以表示为 [1,null,3,2,4,null,5,6]


输出将为 [[1],[3,2,4],[5,6]]

为了解决此问题,我们将遵循以下步骤 −

  • 创建一个矩阵 ans

  • 如果 root 为空,则返回 ans

  • 创建一个队列 q 并插入根

  • 当 q 不为空时

    • size := 队列的大小

    • 创建一个数组 temp

    • 当 size 不为 0 时

      • curr := q 的第一个元素

      • 将 curr 的值插入 temp

      • 从队列中删除元素

      • 对于 curr 的子节点范围为 0 至 size

        • 插入 curr 第 i 个子节点

      • 将 size 减 1

    • 将 temp 插入 ans

  • 返回 ans

让我们看看以下实现以加深理解 −

示例

 在线演示

#include <bits/stdc++.h>
using namespace std;
void print_vector(vector<vector<auto> > v){
   cout << "[";
   for(int i = 0; i<v.size(); i++){
      cout << "[";
      for(int j = 0; j <v[i].size(); j++){
         cout << v[i][j] << ", ";
      }
      cout << "],";
   }
   cout << "]"<<endl;
}
class Node {
   public:
   int val;
   vector<Node*> children;
   Node() {}
   Node(int _val) {
      val = _val;
   }
   Node(int _val, vector<Node*> _children) {
      val = _val;
      children = _children;
   }
};
class Solution {
   public:
   vector<vector<int>> levelOrder(Node* root) {
      vector < vector <int> > ans;
      if(!root)return ans;
         queue <Node*> q;
      q.push(root);
      while(!q.empty()){
         int sz = q.size();
         vector<int> temp;
         while(sz--){
            Node* curr = q.front();
            temp.push_back(curr->val);
            q.pop();
            for(int i = 0; i < curr->children.size(); i++){
               q.push(curr->children[i]);
            }
         }
         ans.push_back(temp);
      }
      return ans;
   }
};
main(){
   Node *root = new Node(1);
   Node *left_ch = new Node(3), *mid_ch = new Node(2), *right_ch = new Node(4);
   left_ch->children.push_back(new Node(5));
   left_ch->children.push_back(new Node(6));
   root->children.push_back(left_ch);
   root->children.push_back(mid_ch);
   root->children.push_back(right_ch);
   Solution ob;
   print_vector(ob.levelOrder(root));
}

输入

[1,null,3,2,4,null,5,6]

输出

[[1, ],[3, 2, 4, ],[5, 6, ],]

更新于: 30-Apr-2020

372 次浏览

开启您的 职业生涯

完成课程以获得认证

入门
广告
© . All rights reserved.