LeetCode 559 N叉樹的最大深度
阿新 • • 發佈:2020-07-19
題目描述連結:https://leetcode-cn.com/problems/maximum-depth-of-n-ary-tree/
基本思路:借用佇列的資料結構,進行廣度優先搜尋即可。具體LeetCode程式碼如下:
/* // 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) { while(!root){ return 0; } queue<Node *>q; q.push(root); int len,q_len; int depth=0; Node *p; while(!q.empty()){ len=q.size(); depth+=1; for(int i=0;i<len;++i){ p=q.front(); q.pop(); q_len=p->children.size(); for(int j=0;j<q_len;++j){ q.push(p->children[j]); } } }return depth; } };