559. N 叉树的最大深度

559. N 叉树的最大深度

java1:牛的,方法很整!

class Solution {
    public int maxDepth(Node root) {
        if (root == null) {
            return 0;
        }
        int maxChildDepth = 0;
        List<Node> children = root.children;
        for (Node child : children) {
            int childDepth = maxDepth(child);
            maxChildDepth = Math.max(maxChildDepth, childDepth);
        }
        return maxChildDepth + 1;
    }
}

java2:

class Solution {
    int maxDepth = 0;

    void dfs(Node root, int depth) {
        if (root == null) {
            return;
        }
        maxDepth = Math.max(maxDepth, depth);
        for (int i = 0; i < root.children.size(); i++) {
            dfs(root.children.get(i), depth + 1);
        }
    }
    public int maxDepth(Node root) {
        dfs(root, 1);
        return maxDepth;
    }
}

java3:回溯

class Solution {
    int maxDepth = 0;
    int depth = 0;

    void dfs(Node root) {
        if (root == null) {
            return;
        }
        depth++;
        maxDepth = Math.max(maxDepth, depth);
        for (int i = 0; i < root.children.size(); i++) {
            dfs(root.children.get(i));
        }
        depth--;
    }
    public int maxDepth(Node root) {
        dfs(root);
        return maxDepth;
    }
}

你可能感兴趣的:(LeetCode刷题,算法)