天天看点

leetcode104.二叉树的最大深度

一.题目描述

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

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

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

示例:

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

3
           

/

9 20

/

15 7

返回它的最大深度 3 。

二.题目解析

public int maxDepth(TreeNode root) {
        /*递归算法-深度优先搜索dfs
        时间O(n),空间O(h)
        * */
        if(root == null){
            return 0;
        }
        return Math.max(maxDepth(root.left),maxDepth(root.right)) + 1;
    }
           
leetcode104.二叉树的最大深度

2.

public int maxDepth1(TreeNode root) {
        /*迭代算法-广度优先搜索bfs
        时间O(n),空间O(width)
         * */
        if(root == null){
            return 0;
        }
        Queue queue = new LinkedList<>();
        //初始进入根节点,高度是1
        queue.offer(root);
        int depth = 1;
        while (!queue.isEmpty()){
            //当前队列大小(假设当前处理的是第i层所有节点)
            int count = queue.size();
            for (int i = 0; i < count; i++) {
                //依次弹出第i层最前面的节点
                TreeNode cur = (TreeNode)queue.poll();
                //判断左右孩子
                if(cur.left != null){
                    queue.offer(cur.left);
                }
                if(cur.right != null){
                    queue.offer(cur.right);
                }
            }
           //第i层所有节点已经出列,如果队列不为空,说明有下一层节点,depth+1
            if(queue.size() != 0){
                depth++;
            }
        }
        return depth;
    }
           
leetcode104.二叉树的最大深度