LeetCode559. Maximum depth of N-ary tree

topic

559. Maximum Depth of N-ary Tree

Given an N-ary tree, find its maximum depth.

The maximum depth refers to the total number of nodes on the longest path from the root node to the farthest leaf node.

N-ary tree input is serialized representation in level-order traversal, with each group of child nodes separated by nulls (see example).

Example 1:
insert image description here

输入:root = [1,null,3,2,4,null,5,6]
输出:3

Example 2:
insert image description here

输入:root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14]
输出:5

hint:

  • The depth of the tree will not exceed 1000.
  • The number of nodes in the tree lies [0, 104]between .

code

/*
// 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) {
    
    
        queue<Node*> que;
        int depth = 0;
        if (root) que.push(root);
        while(!que.empty()) {
    
    
            int size = que.size();
            depth++;
            for (int i = 0; i < size; i++) {
    
    
                Node* s = que.front();
                que.pop();
                for (int j = 0; j < s->children.size(); j++) {
    
    
                    if (s->children[j]) que.push(s->children[j]);
                }
            }
        }
        return depth;
    }
};

Guess you like

Origin blog.csdn.net/Star_ID/article/details/126455583