Given a n-ary tree, find its maximum depth.html
The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.node
For example, given a 3-ary
tree:數組
We should return its max depth, which is 3.函數
Note:post
1000
.5000
.
這道題讓咱們求一個N叉樹的最大深度,因爲以前作過 Maximum Depth of Binary Tree 那道題,因此有了求二叉樹的基礎後,求N叉樹也就不難了,無非就是稍稍變換了一下嗎,由固定的左右子結點變成了一個一堆子結點,可是方法仍是沒有變。首先來看一種常見的遞歸解法,就是須要有一個當前深度,而後帶一個全局變量res進去。在遞歸函數中,若是node爲空,直接返回。若子結點數組爲空,那麼結果res和cur比較取較大值。不然就遍歷子結點數組,對每一個子結點調用遞歸函數,這裏的cur要自增1,參見代碼以下:url
解法一:spa
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,參見代碼以下:code
解法二:htm
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的經典寫法,不算難,參見代碼以下:blog
解法三:
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; } };
相似題目:
參考資料:
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