1. 程式人生 > 實用技巧 >559. N叉樹的最大深度(C++)

559. N叉樹的最大深度(C++)

目錄

題目

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

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

例如,給定一個 3叉樹 :

我們應該返回其最大深度為3。

說明:

  • 樹的深度不會超過 1000
  • 樹的節點總不會超過 5000

分析與題解

自底向上

額外自定義一個將深度作為形參的函式遍歷到葉節點,從葉節點向上增加,每個node更新深度值,取最大的深度,返回深度+1。程式碼如下:

+1是加上本身

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

    Node() {}

    Node(int _val) {
        val = _val;
    }

    Node(int _val, vector<Node*> _children) {
        val = _val;
        children = _children;
    }
};
*/

class Solution {
public:
    int getMaxDepth(Node* root, int depth){
        if(root==nullptr)
            return 0;
        //tmp代表到當前結點的深度
        int tmp = depth;
        for(auto i : root->children){
            //因為迴圈中depth不變,所以取最大值
            //採用臨時遍歷替代
            int node_max = getMaxDepth(i, depth+1);
            //depth值可能是前一個孩子結點
            //每次比較,取孩子中最大的一個
            //depth+1已經體現在遞迴的形參中了
            tmp = max(tmp, node_max);
        }
        return tmp;

    }
    int maxDepth(Node* root) {
        int depth=1;
        return getMaxDepth(root, depth);
    }
};

自頂向下

不需要額外增加自定義函式:

  • 每處理一個節點,深度加一
  • 到達葉節點時,深度計算完畢,然後再層層返回。返回較大值

程式碼如下:

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

    Node() {}

    Node(int _val) {
        val = _val;
    }

    Node(int _val, vector<Node*> _children) {
        val = _val;
        children = _children;
    }
};
*/

class Solution {
public:
    int maxDepth(Node* root) {
        if(root==nullptr)
            return 0;
        //先求出當前結點的孩子結點的最大值
        int depth=0;
        for(auto i : root->children){
            int count = maxDepth(i);
            depth = max(depth, count);
        }
        return depth+1;
    }
};