Number.104——二叉树的最大深度

题目链接:https://leetcode-cn.com/problems/maximum-depth-of-binary-tree/

给定一个二叉树,找出其最大深度。
二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。
说明: 叶子节点是指没有子节点的节点。

给定二叉树 [3,9,20,null,null,15,7],
在这里插入图片描述
返回它的最大深度 3 。

解法一:

用了一种很普通的方法,虽然过了,但效率好像不是特别高。
二叉树层序遍历有一个特点:每次遍历队列中的元素都是二叉树这一层的元素。所以可以根据这个特点来求解深度,也就是二叉树的层数。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public int maxDepth(TreeNode root) {
        if (root == null) return 0;
        Queue<TreeNode> queue = new LinkedList<>();
        int depth = 0;
        queue.offer(root);
        while (!queue.isEmpty()){
            TreeNode nowNode;
            int len = queue.size();
            while (len > 0){	// 把该层元素遍历完
               nowNode = queue.poll();
               if(nowNode.left != null) queue.offer(nowNode.left);
               if(nowNode.right != null) queue.offer(nowNode.right);
               len--;
            }
            depth++;
        }
        return depth;
    }
}

解法二:

代码非常简洁,效率也很高,时间上100%

  1. 如果根为空,则最大深度为0
  2. 求整个数的最大深度,也就是求每个子树的最大深度,然后再加一。也就是左右子树的最大深度。所以可以用递归求解
  3. 求得左右子树中最大深度的最大值,再加一,就是整个子树的最大深度
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public int maxDepth(TreeNode root) {
        return root == null ? 0 : Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章