LeetCode 559 Maximum Depth N-ary Tree

LC Maximum Depth binary Tree

use BFS count the level we are in.


class Solution {
    
    public int maxDepth(Node root) {
        if (root == null) return 0;
        
        Queue<Node> queue = new LinkedList<>();
        queue.offer(root);
        
        int depth = 0;
        
        while (!queue.isEmpty()) {
            int size = queue.size();
            for (int i = 0; i < size; i++) {
                Node cur = queue.poll();
                for (Node child: cur.children) {
                    queue.offer(child);
                }
            }
            depth++;
        }
        return depth;
    }
    
    
}

recursive way:

class Solution {
    
    public int maxDepth(Node root) {
        if (root == null) return 0;
        
        int height = 0;
        for (Node child: root.children) {
            height = Math.max(height, maxDepth(child)); //height get the highest of all the child subtree
        }
        return height + 1; //we need to return the height based on the root of current root
    }
    
    
}

I tried to write recursive like maximum depth of binary tree but I’m just too stupid to get it straight: all i try to use for (int i = 0 to size) and I don’t even don;t know how to deal with return int value problem…I’m so stupid.

posted @ 2020-11-04 12:49  EvanMeetTheWorld  阅读(17)  评论(0)    收藏  举报