본문 바로가기

Algorithm/자료구조

(C++) - LeetCode (easy) 557. Reverse Words in a String III

반응형

https://leetcode.com/problems/maximum-depth-of-n-ary-tree/description/

 

Maximum Depth of N-ary Tree - LeetCode

Can you solve this real interview question? Maximum Depth of N-ary Tree - 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. Nary-Tree input seriali

leetcode.com

재귀적인 tree 순회로 해결한 문제였습니다.

📕 풀이방법

📔 풀이과정

children마다 재귀적으로 호출하며 최대값 + 1 한 값을 저장해 반환합니다.


📕 Code

📔 C++

/*
// Definition for a Node.
class Node {
public:
    int val;
    vector<Node*> children;

    Node() {}

    Node(int _val) {
        val = _val;
    }

    Node(int _val, vector<Node*> _children) {
        val = _val;
        children = _children;
    }
};
*/

class Solution {
public:
    int maxDepth(Node* root) {
        if(root == NULL) return 0;
        int length = 0;
        for(auto nextNode : root->children) {
            length = max(length, maxDepth(nextNode));
        }
        return length + 1;
    }
};

*더 나은 내용을 위한 지적, 조언은 언제나 환영합니다.