559. N 叉树的最大深度

559. N 叉树的最大深度

题目链接:559. N 叉树的最大深度

题解

思路:该题的解法与104. 二叉树的最大深度(层次遍历—使用队列迭代)以及104. 二叉树的最大深度(递归法) 一样。

代码(C++):

//递归法
//后序遍历
class Solution1 {
public:
    int maxDepth(Node* root) {
        if (root == nullptr) return 0;
        int size = root->children.size();
        int result = 0;
        for (int i = 0; i < size; i++) {
            int level = maxDepth(root->children[i]);
            result = result > level ? result : level;
        }
        return result + 1;
    }
};
​
//递归法
//前序遍历
class Solution2 {
public:
    int result;
    void getDepth(Node* node, int depth) {
        result = result > depth ? result : depth;
        if (node->children.empty()) return;
        int size = node->children.size();
        for (int i = 0; i < size; i++) {
            depth++; //深度+1
            getDepth(node->children[i], depth);
            depth--; //回溯 深度-1
        }
        return;
    }
​
    int maxDepth(Node* root) {
        result = 0;
        if (root == nullptr) return result;
        getDepth(root,1);
        return result;
    }
};
​
//迭代法(队列)
//层次遍历
class Solution3 {
public:
    int maxDepth(Node* root) {
        queue<Node*> que;
        if (root != nullptr) que.push(root);
        int depth = 1;
        while (!que.empty()) {
            int size = que.size();
            for (int i = 0; i < size; i++) {
                Node* node = que.front();
                que.pop();
                for (int i = 0; i < node->children.size(); i++) {
                    que.push(node->children[i]);
                }
            }
            depth++;
        }
        return depth - 1;
    }
};

 

 

posted @ 2021-11-30 14:41  wltree  阅读(32)  评论(0编辑  收藏  举报