快轉到主要內容
leetcode 104 - Maximum Depth of Binary Tree

leetcode 104 - Maximum Depth of Binary Tree

·
類別 
Leetcode
標籤 
Java Leetcode Easy BFS Problem DFS Problem Tree Problem Blind75
Eason Chiu
作者
Eason Chiu
一個不做筆記就容易忘記的工程師
目錄

題目
#

leetcode 104 - Maximum Depth of Binary Tree (題目說明請點連結)

題目簡述
#

找出二元樹的最大深度。

範例
#

Example 1:

Input: root = [3,9,20,null,null,15,7]
Output: 3
Explanation: 二元樹的最大深度為 3,從根節點到最遠葉節點的路徑長度。

Example 2:

Input: root = [1,null,2]
Output: 2
Explanation: 二元樹的最大深度為 2,從根節點到最遠葉節點的路徑長度。

解題思路
#

這題要求我們找到二元樹的最大深度。二元樹的最大深度是指從根節點到最遠葉節點的最長路徑上的節點數。 我們可以使用遞迴(DFS)或迭代(BFS)的方式來解決。

解法
#

方法一:遞迴(DFS)
#

使用遞迴的方式,對於每個節點:

  1. 如果節點為空,返回 0
  2. 否則,返回左子樹和右子樹的最大深度 + 1

方法二:迭代(BFS)
#

使用BFS,逐層遍歷二元樹,計算層數。

完整程式碼
#

遞迴解法
#

java
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public int maxDepth(TreeNode root) {
        if (root == null) {
            return 0;
        }
        
        int leftDepth = maxDepth(root.left);
        int rightDepth = maxDepth(root.right);
        
        return Math.max(leftDepth, rightDepth) + 1;
    }
}

迭代解法(BFS)
#

java

import java.util.Queue;
import java.util.LinkedList;

class Solution {
    public int maxDepth(TreeNode root) {
        if (root == null) {
            return 0;
        }
        
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        int depth = 0;
        
        while (!queue.isEmpty()) {
            int levelSize = queue.size();
            
            for (int i = 0; i < levelSize; i++) {
                TreeNode current = queue.poll();
                
                if (current.left != null) {
                    queue.offer(current.left);
                }
                if (current.right != null) {
                    queue.offer(current.right);
                }
            }
            
            depth++;
        }
        
        return depth;
    }
}

時間複雜度
#

  • 時間複雜度:O(n),其中 n 是二元樹中的節點數
  • 空間複雜度
    • 遞迴解法:O(h),其中 h 是二元樹的高度
    • 迭代解法:O(w),其中 w 是二元樹的最大寬度

相關文章

leetcode 199 - Binary Tree Right Side View
類別 
Leetcode
標籤 
Java Leetcode Medium BFS Problem DFS Problem
leetcode 1 - Two Sum
類別 
Leetcode
標籤 
Java Leetcode Easy HashMap Problem Blind75
leetcode 125 - Valid Palindrome
類別 
Leetcode
標籤 
Java Leetcode Easy String Problem Two Pointers Problem Blind75