104. 二叉树的最大深度

给定一个二叉树,找出其最大深度。

二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。

说明: 叶子节点是指没有子节点的节点。

示例:
给定二叉树 [3,9,20,null,null,15,7],

3
/ \
9 20
/ \
15 7
返回它的最大深度 3 。

解法一:深度优先搜索递归版

取左子树和右子树中的最大值加一

public int maxDepth(TreeNode root) {
   return root==null?0:maxDepth(root.left)+maxDepth(root.right)+1;
}

复杂度分析

时间复杂度:O(n)O(n),其中 nn 为二叉树节点的个数。每个节点在递归中只被遍历一次。

空间复杂度:O(\textit{height})O(height),其中 \textit{height}height 表示二叉树的高度。递归函数需要栈空间,而栈空间取决于递归的深度,因此空间复杂度等价于二叉树的高度。

 

解法二:广度优先搜索

从根节点开始遍历每一层,把当前层的所有子节点都加入队列,同时层数加一

public int maxDepth(TreeNode root) {
        if (root == null)
            return 0;
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        int length = 0;
        while(!queue.isEmpty()) {
            length += 1;
            int size = queue.size();
            while(size>0) {
                TreeNode node = queue.poll();
                if(node.left!=null)
                    queue.add(node.left);
                if(node.right!=null)
                    queue.add(node.right);
                size--;
            }
        }
        return length;
    }

复杂度分析

时间复杂度:O(n)O(n),其中 nn 为二叉树的节点个数。与方法一同样的分析,每个节点只会被访问一次。

空间复杂度:此方法空间的消耗取决于队列存储的元素数量,其在最坏情况下会达到 O(n)O(n)。

解法三:深度优先搜索的迭代版

思路:把根节点和它的深度入栈,然后把它的右节点和左节点入栈,同时深度加一,然后这个当前这个节点的寿命就消亡了,然后把它的左节点的右节点和左节点加入栈,不断迭代,直到节点为空

 /**
     * DFS迭代实现二叉树最大深度
     * 时间复杂度O(n)
     * 空间复杂度:线性表最差O(n)、二叉树完全平衡最好O(logn)
     *
     * @param root 根节点
     * @return 最大深度
     */
    private static int maxDepth2(TreeNode root) {
        if (root == null) {
            return 0;
        }
        LinkedList<Pair<TreeNode, Integer>> stack = new LinkedList<>();
        stack.push(new Pair<>(root, 1));
        int maxDepth = 0;
        //DFS实现前序遍历,每个节点记录其所在深度
        while (!stack.isEmpty()) {
            Pair<TreeNode, Integer> pair = stack.pop();
            TreeNode node = pair.first;
            //DFS过程不断比较更新最大深度
            maxDepth = Math.max(maxDepth, pair.second);
            //记录当前节点所在深度
            int curDepth = pair.second;
            //当前节点的子节点入栈,同时深度+1
            if (node.right != null) {
                stack.push(new Pair<>(node.right, curDepth + 1));
            }
            if (node.left != null) {
                stack.push(new Pair<>(node.left, curDepth + 1));
            }
      }
        return maxDepth;
    }

 

posted @ 2021-06-10 10:09  zhustarstar  阅读(84)  评论(0编辑  收藏  举报