104. Maximum Depth of Binary Tree(二叉树的最大深度)

题目描述

方法思路

Approach1: recursive

class Solution {
    public int maxDepth(TreeNode root) {
        if(root == null) return 0;
        int depth = 0;
        int left_depth = maxDepth(root.left);
        int right_depth = maxDepth(root.right);
        depth = left_depth > right_depth ? left_depth : right_depth;
        return depth + 1;
    }
}

简化版本

class Solution {
    //Runtime: 0 ms, faster than 100.00%
    //Memory Usage: 40.1 MB, less than 5.01%
    public int maxDepth(TreeNode root) {
        if(root == null) return 0;
        return Math.max(maxDepth(root.left),maxDepth(root.right)) + 1;
    }
}

Approach2: DFS

class Solution {
    //Runtime: 3 ms, faster than 5.70%
    //Memory Usage: 39.9 MB, less than 6.34%
    public int maxDepth(TreeNode root) {
    if(root == null) {
        return 0;
    }
    
    Stack<TreeNode> stack = new Stack<>();
    Stack<Integer> value = new Stack<>();
    stack.push(root);
    value.push(1);
    int max = 0;
    while(!stack.isEmpty()) {
        TreeNode node = stack.pop();
        int temp = value.pop();
        max = Math.max(temp, max);
        if(node.left != null) {
            stack.push(node.left);
            value.push(temp+1);
        }
        if(node.right != null) {
            stack.push(node.right);
            value.push(temp+1);
        }
    }
    return max;
}
}

Approach3: BFS
层序遍历

class Solution {
    //Runtime: 1 ms, faster than 17.00%
    //Memory Usage: 39.9 MB, less than 6.34%
    public int maxDepth(TreeNode root) {
    if(root == null) {
        return 0;
    }
    Queue<TreeNode> queue = new LinkedList<>();
    queue.offer(root);
    int count = 0;
    while(!queue.isEmpty()) {
        int size = queue.size();
        while(size-- > 0) {
            TreeNode node = queue.poll();
            if(node.left != null) {
                queue.offer(node.left);
            }
            if(node.right != null) {
                queue.offer(node.right);
            }
        }
        count++;
    }
    return count;
}
}

猜你喜欢

转载自blog.csdn.net/IPOC_BUPT/article/details/88342259