原题链接

思路:

递归计算每个子树的深度,返回最大深度即可

 

python/python3:

class Solution(object):
    def maxDepth(self, root):
        """
        :type root: Node
        :rtype: int
        """
        if root:
            if root.children:
                return max([self.maxDepth(child) for child in root.children]) + 1
            else:
                return 1
        else:
            return 0

 

C++:

class Solution {
public:
    int maxDepth(Node* root) {
        if(root == NULL){
            return 0;
        }   
        else{
            if(root->children.size() != 0){
                vector<int> chs;
                for(auto child:root->children){
                    chs.push_back(maxDepth(child));
                }
                return *max_element(chs.begin(), chs.end()) + 1;
            }
            else{
                return 1;
            }
        }
    }
};

 

posted on 2020-07-22 15:45  CopyLeft  阅读(85)  评论(0)    收藏  举报