Given a n-ary tree, find its maximum depth.

The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

解法比较简单,DFS和BFS两种方法

1.BFS

/*
// Definition for a Node.
class Node {
    public int val;
    public List<Node> children;

    public Node() {}

    public Node(int _val,List<Node> _children) {
        val = _val;
        children = _children;
    }
};
*/
class Solution {
    public int maxDepth(Node root) {
        if(root == null)
            return 0;

        int depth = 0;
        LinkedList<Node> curr = new LinkedList<Node>();
        LinkedList<Node> next = new LinkedList<Node>();

        curr.offer(root);

        while(curr.size() > 0) {
            Node temp = curr.poll();
            if(temp.children != null && temp.children.size() != 0) {
                for(Node child: temp.children) {
                    next.offer(child);
                }
            }

            if(curr.size() == 0) {
                depth++;
                curr = next;
                next = new LinkedList<Node>();
            }
        }

        return depth;
    }
}

2.DFS

/*
// Definition for a Node.
class Node {
    public int val;
    public List<Node> children;

    public Node() {}

    public Node(int _val,List<Node> _children) {
        val = _val;
        children = _children;
    }
};
*/
class Solution {
    private int depth = 0;
    public int maxDepth(Node root) {
        if(root == null)
            return 0;

        dfs(root, 1);
        return depth;
    }

    public void dfs(Node root, int currDepth) {
        this.depth = Math.max(this.depth, currDepth);

        if(root.children != null && root.children.size() != 0) {
            for(Node child: root.children) {
                dfs(child, currDepth + 1);
            }
        }
    }
}

results matching ""

    No results matching ""