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

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

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

leedcode题集: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;
    }
};