【leetcode】559 N叉樹的最大深度(DFS+BFS兩種解法)

給定一個 N 叉樹,找到其最大深度。

最大深度是指從根節點到最遠葉子節點的最長路徑上的節點總數。

例如,給定一個 3叉樹 :

 

 

我們應返回其最大深度,3。

說明:

樹的深度不會超過 1000。
樹的節點總不會超過 5000。

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;//條件1
        int max = 0;
        for(Node cur:root.children){
            int depth = maxDepth(cur);
            max = Math.max(max,depth);
        }
        return max+1;//遞歸結束條件2    
    }
}

BFS

/*
// 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 max = 0;
        Queue<Node> queue = new LinkedList<>();
        queue.offer(root);
        while(!queue.isEmpty()){
            int size = queue.size();
            max++;
            while(size>0){
                size--;
                Node cur = queue.poll();
                for(Node curr:cur.children){
                    queue.offer(curr);
                }
            }
        }   
        return max;
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章