April 19, 2019

104. Maximum Depth of Binary Tree

104. Maximum Depth of Binary Tree

法1. DFS Recursion (Divide and Conquer)

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

法2. DFS Recursive (Traverse)

class Solution {
    int maxDepth;
    public int maxDepth(TreeNode root) {
        maxDepth = 0;
        dfsHelper(root, 1);
        return maxDepth;
    }
    
    private void dfsHelper(TreeNode root, int depth) {
        if (root == null) {
            return;
        }
        if (depth > maxDepth) {
            maxDepth = depth;
        }
        dfsHelper(root.left, depth + 1);
        dfsHelper(root.right, depth + 1);
    }
}

法3. DFS Iterative

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public int maxDepth(TreeNode root) {
        if (root == null) {
            return 0;
        }
        
        Deque<TreeNode> stack = new LinkedList<>();
        Deque<Integer> depth = new LinkedList<>();
        
        stack.push(root);
        depth.push(1);
        
        int maxDepth = 0;
        
        while (!stack.isEmpty()) {
            TreeNode curNode = stack.pollFirst();
            int curDepth = depth.pollFirst();
            
            maxDepth = Math.max(curDepth, maxDepth);
            
            if (curNode.left != null) {
                stack.offerFirst(curNode.left);
                depth.offerFirst(curDepth + 1);
            }
            
            if (curNode.right != null) {
                stack.offerFirst(curNode.right);
                depth.offerFirst(curDepth + 1);
            }            
        }
        
        return maxDepth;
    }
}

法4. BFS Iterative

本解法本质就是 BFS 树的遍历,参考 102. Binary Tree Level Order Traversal

class Solution {
    public int maxDepth(TreeNode root) {
        if (root == null) {
            return 0;
        }
        
        Queue<TreeNode> queue = new LinkedList<>();
        int maxDepth = 0;
        
        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);
                }
            }
            maxDepth++;
        }
        return maxDepth;
        
    }
}

所有解法 Time Complexity 均为 O(n),Space Complexity 为 O(h)。

comments powered by Disqus