LeetCode:559. Maximum Depth of N-ary Tree

題目要求

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.
給定一個(gè)n-樹,求其最大深度。


舉例.PNG

題目分析

本題要求的一棵樹的最大深度,其實(shí)就是求一顆樹的深度,也可以理解成求根節(jié)點(diǎn)的深度,關(guān)于樹的深度請參考:

所以可以將這個(gè)問題分冶。即將求一個(gè)節(jié)點(diǎn)的深度轉(zhuǎn)換成求其子節(jié)點(diǎn)的最大深度+1,這個(gè)思想可以用遞歸的方法來實(shí)現(xiàn)。

本題解析

/*
// 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) {
        
        if( !root )
            return 0;

        int depth = 0;
        
        for( auto &child: root->children )
        {    /*遍歷子節(jié)點(diǎn)*/
            depth = max( depth, maxDepth(child));      /*求出子節(jié)點(diǎn)的最大深度*/
        }
        
        return depth + 1;    /*返回子節(jié)點(diǎn)的最大深度 + 1*/
        
    }
};
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容