1. 程式人生 > 其它 >LeetCode 0104 Maximum Depth of Binary Tree

LeetCode 0104 Maximum Depth of Binary Tree

原題傳送門

1. 題目描述

2. Solution 1

1、思路分析
遞迴實現
1> 遞迴出口。遍歷當前結點為空,返回0。
2> 遞迴分解。當前高度=max{左子樹高度,右子樹高度} +1。

2、程式碼實現

package Q0199.Q0104MaximumDepthofBinaryTree;

import DataStructure.TreeNode;

/*
    Depth first search
 */
public class Solution1 {
    public int maxDepth(TreeNode root) {
        return root == null ? 0 : Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;
    }
}

3、複雜度分析
時間複雜度: O(n)
空間複雜度: O(height),height為樹高度。

3. Solution 2

1、思路分析
層次遍歷,統計層數即為樹高。

2、程式碼實現

package Q0199.Q0104MaximumDepthofBinaryTree;

import DataStructure.TreeNode;

import java.util.ArrayDeque;
import java.util.Queue;

/*
    Level travel, Calculate the count of the last level.
 */
public class Solution2 {
    public int maxDepth(TreeNode root) {
        if (root == null) return 0;
        int res = 0;
        Queue<TreeNode> queue = new ArrayDeque<>();
        queue.add(root);
        while (!queue.isEmpty()) {
            ++res;
            for (int i = 0, n = queue.size(); i < n; i++) {
                TreeNode p = queue.peek();
                queue.poll();

                if (p.left != null) queue.add(p.left);
                if (p.right != null) queue.add(p.right);
            }
        }
        return res;
    }
}

3、複雜度分析
時間複雜度: O(n)
空間複雜度: O(n)