104. Maximum Depth of Binary Tree

思路

遞歸/深度優先搜索, 維持一個全局變量記錄深度node

複雜度

時間複雜度O(n)code

代碼

//遞歸
class Solution {
    int maxDepth = 0;
    public int maxDepth(TreeNode root) {
        if (root == null) {
            return 0;
        }
        helper(root, 1);
        return maxDepth;
    }
    private void helper(TreeNode node, int cur) {
        if (node == null) {
            return;
        }
        maxDepth = Math.max(cur, maxDepth);
        helper(node.left, cur + 1);
        helper(node.right, cur +1);
    }
}

思路

分治法遞歸

複雜度

時間複雜度O(n)io

代碼

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

思路

廣度優先搜索的方法, 用queue來記錄樹的節點class

複雜度

時間複雜度O(n) 空間複雜度O(log n)變量

代碼

//BFS
class Solution {
    int maxDepth = 0;
    public int maxDepth(TreeNode root) {
        if (root == null) {
            return 0;
        }
        int depth = 0;
        Queue<TreeNode> queue = new LinkedList<TreeNode>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            int size = queue.size();
            for (int i = 0; i <size; i++) {
                TreeNode cur = queue.poll();
                if (cur.left != null) {
                    queue.offer(cur.left);
                }
                if (cur.right != null) {
                    queue.offer(cur.right);
                }
            }
            depth++;
        }
        return depth;
    }
}
相關文章
相關標籤/搜索