天天看點

本題要求給定二叉樹的4種周遊。_104. 二叉樹的最大深度

本題要求給定二叉樹的4種周遊。_104. 二叉樹的最大深度

104. 二叉樹的最大深度

給定一個二叉樹,找出其最大深度。

二叉樹的深度為根節點到最遠葉子節點的最長路徑上的節點數。

說明: 葉子節點是指沒有子節點的節點。

示例: 給定二叉樹

[3,9,20,null,null,15,7]

3
   / 
  9  20
    /  
   15   7
           

傳回它的最大深度

3

作者:力扣 (LeetCode) 連結:https://leetcode-cn.com/leetbook/read/data-structure-binary-tree/xefh1i/ 來源:力扣(LeetCode) 著作權歸作者所有。商業轉載請聯系作者獲得授權,非商業轉載請注明出處。

題解:

本題就是簡單的

DFS

的應用,沒有什麼特殊的技巧,通過遞歸,循環周遊整棵樹。

具體代碼如下:

class Solution {
    public int maxDepth(TreeNode root) {
        if (root == null) return 0;
        int left = maxDepth(root.left);
        int right = maxDepth(root.right);
        return Math.max(left, right) + 1;
    }
}
           

本題也可用

BFS

做,但是時間複雜度不如深度優先搜尋周遊。

具體代碼如下:

class Solution {
    public int maxDepth(TreeNode root) {
        int depth = 0;
        if (root == null) {
            return 0;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);

        while (!queue.isEmpty()) {
            int len = queue.size();
            for (int i = 0; i < len; i++) {
                TreeNode node = queue.poll();
                if (node.left != null) {
                    queue.add(node.left);
                }
                if (node.right != null) {
                    queue.add(node.right);
                }
            }
            depth++;
        }
        return depth;
    }
}
           

繼續閱讀