LeetCode559.N 叉树的最大深度

题目

法一、层序遍历

 1 class Solution {
 2 public:
 3     int maxDepth(Node* root) {
 4         if(root== NULL) return 0;
 5         queue<Node*>q;int level = 0;int lc = 0;
 6         q.push(root);
 7         while(!q.empty()){
 8             lc = q.size();
 9             for(int i = 0;i < lc;i++){
10                 Node* p = q.front();q.pop();
11                 for(int j = 0;j < p->children.size();j++){
12                 q.push(p->children[j]);
13                 }
14             }
15             level++;
16         }
17         return level;
18     }
19 };

法二、递归

 1 class Solution {
 2 public:
 3     int maxDepth(Node* root) {
 4         if(root == NULL) return 0;
 5         int depth = 0;
 6         for(int i = 0;i < root->children.size();i++)
 7             depth = max(depth,maxDepth(root->children[i]));
 8         return depth+1;
 9     }
10 };
原文地址:https://www.cnblogs.com/fresh-coder/p/14258518.html