0
点赞
收藏
分享

微信扫一扫

BM28 二叉树的最大深度

在这里插入图片描述
第一种:用集合来存储已经走的层数,最后返回集合的大小就是最大的层数,时间复杂度O(n),空间复杂度O(n)

import java.util.*;

/*
 * public class TreeNode {
 *   int val = 0;
 *   TreeNode left = null;
 *   TreeNode right = null;
 * }
 */

public class Solution {
    /**
     *
     * @param root TreeNode类
     * @return int整型
     */
    public int maxDepth (TreeNode root) {
        // write code here
        if (root == null) {
            return 0;
        }
        Set<Integer> set = new HashSet<>();
        //depth = 1 表示从第一层开始遍历
        //set保存的就是层数
        getDepth(root, set, 1);
        return set.size();
    }

    private void getDepth(TreeNode root, Set<Integer> set, int depth) {
        if (root == null) {
            return ;
        }
        set.add(depth);
        getDepth(root.left, set, depth + 1);
        getDepth(root.right, set, depth + 1);
    }
}

第二种:用一个变量表示最大层数,时间复杂度O(n),空间复杂度O(1)

import java.util.*;

/*
 * public class TreeNode {
 *   int val = 0;
 *   TreeNode left = null;
 *   TreeNode right = null;
 * }
 */

public class Solution {
    /**
     *
     * @param root TreeNode类
     * @return int整型
     */
    private int max = 0;
    public int maxDepth (TreeNode root) {
        // write code here
        if (root == null) {
            return 0;
        }
        //depth = 1 表示从第一层开始遍历
        //max表示最大层数
        getDepth(root, 1);
        return max;
    }

    private void getDepth(TreeNode root, int depth) {
        if (root == null) {
            return ;
        }
        max = max > depth ? max : depth;
        getDepth(root.left, depth + 1);
        getDepth(root.right, depth + 1);
    }
}

第三种:递归求解,因为题目是求root的最高深度,也就是求max(root.left,root.right)的最大值+1,依次递归即可,时间复杂度O(n),空间复杂度O(1)

import java.util.*;

/*
 * public class TreeNode {
 *   int val = 0;
 *   TreeNode left = null;
 *   TreeNode right = null;
 * }
 */

public class Solution {
    /**
     *
     * @param root TreeNode类
     * @return int整型
     */
    public int maxDepth (TreeNode root) {
        // write code here
        if (root == null) {
            return 0;
        }
        return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;
    }

}
举报

相关推荐

0 条评论