[LeetCode] N-ary Tree Level Order Traversal N叉樹層序遍歷

 

Given an n-ary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).html

For example, given a 3-ary tree:node

 

 

We should return its level order traversal:數組

 

 

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

 

Note:函數

  1. The depth of the tree is at most 1000.
  2. The total number of nodes is at most 5000.

 

這道題給了咱們一棵N叉樹,讓咱們對其進行層序遍歷。咱們作過以前二叉樹的層序遍歷的那道題的話Binary Tree Level Order Traversal,那麼這道題也就不難了。雖然說如今每個結點可能有不少個子結點,但其實處理的思路的都是同樣的。子結點放到了一個children數組中,咱們訪問的時候只要遍歷數組就好了。先來看迭代的寫法,用到了隊列queue來輔助,首先判斷root是否爲空,爲空直接返回空數組,不然加入queue中。而後遍歷queue,這裏用的trick就是,要加個for循環,要將當前queue中的結點的個數統計下來,由於再加入下一層的結點時,queue的結點個數會增長,而在加入下一層結點以前,當前queue中的結點個數全都屬於一層,因此咱們要把層與層區分開來,將同一層的結點都放到一個數組out中,以後再放入結果res中,這種層序遍歷的思想在迷宮遍歷找最短路徑的時候應用的也不少,是個必需要掌握的方法呢,參見代碼以下:spa

 

解法一:code

class Solution {
public:
    vector<vector<int>> levelOrder(Node* root) {
        if (!root) return {};
        vector<vector<int>> res;
        queue<Node*> q{{root}};
        while (!q.empty()) {
            vector<int> out;
            for (int i = q.size(); i > 0; --i) {
                auto t = q.front(); q.pop();
                out.push_back(t->val);
                if (!t->children.empty()) {
                    for (auto a : t->children) q.push(a);
                }
            }
            res.push_back(out);
        }
        return res;
    }
};

 

下面再來看遞歸的寫法,其實層序遍歷自然適合迭代的寫法,但咱們強行遞歸也是能夠的,就是有點秀。因爲遞歸DFS的設定是一條路走到黑再返回,那麼必然會跨越不一樣的層數,因此爲了區別當前的層,咱們須要一個變量level來標記當前的層數,根結點root就是第0層,依此類推往上加。而後還有個trick就是關於結果res的大小,因爲咱們並不知道樹的深度,因此一旦咱們遍歷的層數超過了當前res的大小,咱們須要resize一下,這樣纔不會出錯。以後,咱們將當前遍歷到的結點加到res中的第level層中,而後遍歷子結點數組,對每個子結點調用遞歸函數便可,參見代碼以下:htm

 

解法二:blog

class Solution {
public:
    vector<vector<int>> levelOrder(Node* root) {
        vector<vector<int>> res;
        helper(root, 0, res);
        return res;
    }
    void helper(Node* node, int level, vector<vector<int>>& res) {
        if (!node) return;
        if (res.size() <= level) res.resize(res.size() + 1);
        res[level].push_back(node->val);
        for (auto a : node->children) {
            helper(a, level + 1, res);
        }
    }
};

 

相似題目:遞歸

Binary Tree Level Order Traversal隊列

N-ary Tree Preorder Traversal

N-ary Tree Postorder Traversal

 

參考資料:

https://leetcode.com/problems/n-ary-tree-level-order-traversal/description/

https://leetcode.com/problems/n-ary-tree-level-order-traversal/discuss/156218/Typical-C++-recursive-solution

 

LeetCode All in One 題目講解彙總(持續更新中...)

相關文章
相關標籤/搜索