LeetCode - N叉樹的最大深度

題目鏈接:https://leetcode-cn.com/problems/search-a-2d-matrix/submissions/

題目描述

給定一個 N 叉樹,找到其最大深度。

最大深度是指從根節點到最遠葉子節點的最長路徑上的節點總數。

例如,給定一個 3叉樹 :
3叉樹
我們應返回其最大深度,3。

說明:

  1. 樹的深度不會超過 1000。
  2. 樹的節點總不會超過 5000。

我的思路

  • 繼上一道 easy 難度二叉樹的題之後,又一道關於遞歸的 easy 難度題差點把我坑住,最近智商堪憂。
  • 思路和求二叉樹深度一樣。
  • 自底向上大法,每個子節點的深度都取其孩子節點中深度最大的,一直往上走直到根節點。

代碼如下:

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

    Node() {}

    Node(int _val, vector<Node*> _children) {
        val = _val;
        children = _children;
    }
};
*/
class Solution {
public:
    int maxDepth(Node* root) {
        int depth = 1;
        if(!root) return 0;
        for(int i = 0; i < root->children.size(); i++){
            depth = max(maxDepth(root->children[i]) + 1,  depth);
        }
        return depth;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章