[LeetCode] Maximum Depth of N-ary Tree N叉樹的最大深度


 

Given a n-ary tree, find its maximum depth.

The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

For example, given a 3-ary tree:

 

 

We should return its max depth, which is 3.

 

Note:

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

 

這道題讓我們求一個N叉樹的最大深度,由於之前做過 Maximum Depth of Binary Tree 那道題,所以有了求二叉樹的基礎后,求N叉樹也就不難了,無非就是稍稍變換了一下嗎,由固定的左右子結點變成了一個一堆子結點,但是方法還是沒有變。首先來看一種常見的遞歸解法,就是需要有一個當前深度,然后帶一個全局變量res進去。在遞歸函數中,如果node為空,直接返回。若子結點數組為空,那么結果res和cur比較取較大值。否則就遍歷子結點數組,對每個子結點調用遞歸函數,這里的cur要自增1,參見代碼如下:

 

解法一:

class Solution {
public:
    int maxDepth(Node* root) {
        int res = 0;
        helper(root, 1, res);
        return res;
    }
    void helper(Node* node, int cur, int& res) {
        if (!node) return;
        if (node->children.empty()) res = max(res, cur);
        for (Node* child : node->children) {
            helper(child, cur + 1, res);
        }
    }
};

 

我們也可以不使用其他的函數,直接主函數中遞歸,首先判空,否則就是遍歷子結點數組,然后對每個子結點調用遞歸函數的返回值加1后跟res相比,取較大值更新結果res,參見代碼如下:

 

解法二:

class Solution {
public:
    int maxDepth(Node* root) {
        if (!root) return 0;
        int res = 1;
        for (Node* child : root->children) {
            res = max(res, maxDepth(child) + 1);
        }
        return res;
    }
};

 

我們也可以不使用遞歸,而是用迭代的形式,這里借助隊列queue來做,就是BFS的經典寫法,不算難,參見代碼如下:

 

解法三:

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

 

類似題目:

Maximum Depth of Binary Tree

 

參考資料:

https://leetcode.com/problems/maximum-depth-of-n-ary-tree/

https://leetcode.com/problems/maximum-depth-of-n-ary-tree/discuss/148544/Java-Top-down-DFS-solutions

https://leetcode.com/problems/maximum-depth-of-n-ary-tree/discuss/167010/DFS-and-BFS-solutions-in-C%2B%2B.

https://leetcode.com/problems/maximum-depth-of-n-ary-tree/discuss/151804/Solution-Python-C%2B%2B-Simple-with-explanation

 

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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM