LeetCode 给定一个 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) {
         int depth = 1;
        if(root == NULL)
            return 0;
        else
        {
            int max = 0;
            for(int i = 0;i<root->children.size();i++)
            {
               int n = 1 + maxDepth(root->children.at(i));
                max = (max < n)?n:max;
            }
            
            depth = (depth >max)?depth:max;
            return depth;
        }
    }
};

思考:

N叉树 要遍历每个子叉树,所以,可以从向量 size读取。然后判断最大叉树的 深度。

坑: 只有一个节点的深度=1;

猜你喜欢

转载自blog.csdn.net/xiuscut/article/details/83861994