leetcode题集:559. Maximum Depth of N-ary Tree

2 篇文章 0 订阅
2 篇文章 0 订阅

最近开始刷leetcode,博客以作记录。

第一天:559. Maximum Depth of N-ary Tree

给定树的数据结构定义:

/*
// 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) {

    }
};

一道水题,给定树的数据结构定义,求树的高度,用DFS即可。有一点需要注意的地方,就是递归的终止条件,如果本身是空指针,则返回0;如果该节点的子节点为空,则也无需继续往下循环,返回结果1。完整代码如下:

class Solution {
public:
    int maxDepth(Node* root) {
        if(root == NULL) return 0;
        if(root->children.size() == 0) return 1;
        int maxdepth = 0;
        for(int i=0;i<root->children.size();i++){
            int depth = 1 + maxDepth(root->children[i]);
            // cout <<depth <<endl;
            maxdepth = (maxdepth > depth)? maxdepth : depth;
        }
        return maxdepth;
    }
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值