Files
leetcode-master/problems/0559.N叉树的最大深度.md
youngyangyang04 c0be90a277 Update
2020-09-29 10:08:39 +08:00

950 B

地址

思路

C++代码

递归法

class Solution {
public:
    int maxDepth(Node* root) {
        if (root == 0) return 0;
        int depth = 0;
        for (int i = 0; i < root->children.size(); i++) {
            depth = max (depth, maxDepth(root->children[i]));
        }
        return depth + 1;
    }
};

迭代法

class Solution {
public:
    int maxDepth(Node* root) {
        queue<Node*> que;
        if (root != NULL) que.push(root);
        int depth = 0;
        while (!que.empty()) {
            int size = que.size();
            vector<int> vec;
            depth++;
            for (int i = 0; i < size; i++) {
                Node* node = que.front();
                que.pop();
                for (int i = 0; i < node->children.size(); i++) {
                    if (node->children[i]) que.push(node->children[i]);
                }
            }
        }
        return depth;
    }
};