【leetcode/多叉树】多叉树的层序遍历(BFS)

问题描述:

给定一个 N 叉树,返回其节点值的层序遍历。 (即从左到右,逐层遍历)。

例如,给定一个 3叉树 :

 

 

返回其层序遍历:

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

基本思路:

就是BFS,记录层数的那一种。

AC代码:

/*
// Definition for a Node.
class Node {
public:
    int val;
    vector children;

    Node() {}

    Node(int _val, vector _children) {
        val = _val;
        children = _children;
    }
};
*/
class Solution {
public:
    // 多叉树的层序遍历其实就是BFS
    vector> levelOrder(Node* root) {
      vector> res;
      if (!root) return res;
      queue q;
      q.push(root);
      int width = q.size();
      while (!q.empty()) {
        vector row;
        for (int i = 0; i < width; ++i) {
          auto v = q.front();
          q.pop();
          row.push_back(v->val);
          auto neighbors = v->children;
          for (auto n : neighbors) {
            q.push(n);
          }
        }
        res.push_back(row);
        width = q.size();
      }
      return res;  
    }
};

 

说明:

  1. 树的深度不会超过 1000
  2. 树的节点总数不会超过 5000

你可能感兴趣的:(#,多叉树)