[leetcode] Maximum Depth of N-ary Tree

jun·2021년 4월 6일
0
post-thumbnail

유의할점

size = 0 인경우

풀이

코드

Java : 내가 짠 코드 , 내부 while


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

    public Node() {}

    public Node(int _val) {
        val = _val;
    }

    public Node(int _val, List<Node> _children) {
        val = _val;
        children = _children;
    }
};
*/

class Solution {
    public int maxDepth(Node root) {
        if(root==null)
            return 0;
        int res = 0;
        Queue <Node> queue = new LinkedList<>();
        queue.add(root);
        while(!queue.isEmpty()){
            int size = queue.size();
            while(size!=0){
                Node e = queue.poll();
                for(Node n : e.children)
                    queue.add(n);
                size--;
            }
            res++;
        }
        return res;
    }
}

Java : 내가 짠 코드 , 내부 for

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

    public Node() {}

    public Node(int _val) {
        val = _val;
    }

    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;
        Queue <Node> queue = new LinkedList<>();
        queue.add(root);
        while(!queue.isEmpty()){
            int size = queue.size();
            for(int i = 0 ; i < size ; i ++){
                Node e = queue.poll();
                for(Node c : e.children)
                    queue.add(c);
            }
            depth++;
        }
        return depth;
    }
}

Java : DFS로 푸는법.. 생각이 안났다.

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

    public Node() {}

    public Node(int _val) {
        val = _val;
    }

    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;
        for(Node N : root.children) depth = Math.max(depth,maxDepth(N));
        return 1 + depth;
    }
}
profile
Computer Science / Algorithm / Project / TIL

0개의 댓글