LeetCode 559. N叉树的最大深度
生活随笔
收集整理的這篇文章主要介紹了
LeetCode 559. N叉树的最大深度
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
文章目錄
- 1. 題目
- 2. 解題
- 2.1 遞歸
- 2.2 按層queue遍歷
1. 題目
給定一個 N 叉樹,找到其最大深度。
最大深度是指從根節(jié)點到最遠葉子節(jié)點的最長路徑上的節(jié)點總數(shù)。
2. 解題
2.1 遞歸
class Solution { public:int maxDepth(Node* root) {if(root == NULL)return 0;int childDep = 0;for(int i = 0; i < root->children.size(); ++i){childDep = max(childDep, maxDepth(root->children[i]));}return childDep+1;} };2.2 按層queue遍歷
class Solution { public:int maxDepth(Node* root) {if(root == NULL)return 0;int deep = 0;queue<Node*> q;Node *tp;q.push(root);int n, i;while(!q.empty()){++deep;n = q.size();while(n--){tp = q.front();for(i = 0; i < tp->children.size(); ++i)q.push(tp->children[i]);q.pop();}}return deep;} };總結(jié)
以上是生活随笔為你收集整理的LeetCode 559. N叉树的最大深度的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python装饰器由浅入深_由浅入深理解
- 下一篇: 数据结构--二叉查找树 Binary S