LeetCode刷题笔记 104 / 剑指Offer 55 - I(涉及到递归、层次遍历)

题目:二叉树的最大深度
给定一个二叉树,找出其最大深度。
二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。
说明: 叶子节点是指没有子节点的节点。
示例:
给定二叉树 [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7

返回它的最大深度 3 。

答案:
1.递归
思路:树的深度等于1+最大的子树的深度

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

时间复杂度: O(N)
空间复杂度:最坏情况下,树完全不平衡,栈的存储将是 O(N)。最好情况下,树完全平衡, O(log(N))

2.迭代
BFS层次遍历

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

你可能感兴趣的:(LeetCode,剑指Offer,leetcode,java,二叉树)