559. Maximum Depth of N-ary Tree

406 篇文章 0 订阅
406 篇文章 0 订阅

1,题目要求
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.
这里写图片描述
计算一颗多叉树的最大深度。

2,题目思路
求一颗树的最大深度,对于二叉树来说比较简单:

int maxDepth(TreeNode* node)
{
    if(node == nullptr)
        return 0;
    return max(maxDepth(node->left), maxDepth(node->right))+1;
}

当拓展到多叉树时,因为节点是保存在vector中,因此,此时原理和二叉树是相似,只不过不再是仅仅对左右子树进行判断,而是对vector中所有节点都进行判断。

3,程序源码

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 == nullptr) return 0;
        int dep = 0;
        for(auto n : root->children)
            dep = max(dep, maxDepth(n));
        return dep + 1;
    } 
};
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值