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;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章