97.二叉樹的最大深度(高頻++)

描述

給定一個(gè)二叉樹,找出其最大深度。
二叉樹的深度為根節(jié)點(diǎn)到最遠(yuǎn)葉子節(jié)點(diǎn)的距離。

樣例

給出一棵如下的二叉樹:

  1
 / \ 
2   3
     / \
    4   5

這個(gè)二叉樹的最大深度為3.

代碼

/**
 * Definition of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int val) {
 *         this.val = val;
 *         this.left = this.right = null;
 *     }
 * }
 */   
  1. 遍歷
 public class Solution {
    /**
     * @param root: The root of binary tree.
     * @return: An integer.
     */
    // 定義全局變量,因?yàn)?maxDepth 方法和 helper 方法是并列方法,如果把depth定義在 maxDepth 中,helper是沒辦法調(diào)用 depth 變量的
    private int depth;
    
    public int maxDepth(TreeNode root) {
        depth = 0;
        helper(root, 1);
        return depth;
    }
        
    private void helper(TreeNode root, int curDepth) {
        // 遞歸出口
        if (root == null) {
           return;
        }
        if (curDepth > depth) {
            depth = curDepth;
        }
        // 遞歸的分解,每向下一層,深度要加1
        // root.left、root.right 為 0 時(shí)(即 root 是葉子結(jié)點(diǎn)) curDepth + 1 不生效
        helper (root.left, curDepth + 1);
        helper (root.right, curDepth + 1);
    }
}
  1. 分治
public class Solution {
    public int maxDepth(TreeNode root) {
        if (root == null) {
            return 0;
        }

        int left = maxDepth(root.left);
        int right = maxDepth(root.right);

        return Math.max(left, right) + 1;
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 樹的概述 樹是一種非常常用的數(shù)據(jù)結(jié)構(gòu),樹與前面介紹的線性表,棧,隊(duì)列等線性結(jié)構(gòu)不同,樹是一種非線性結(jié)構(gòu) 1.樹的定...
    Jack921閱讀 4,764評(píng)論 1 31
  • 基于樹實(shí)現(xiàn)的數(shù)據(jù)結(jié)構(gòu),具有兩個(gè)核心特征: 邏輯結(jié)構(gòu):數(shù)據(jù)元素之間具有層次關(guān)系; 數(shù)據(jù)運(yùn)算:操作方法具有Log級(jí)的平...
    yhthu閱讀 4,471評(píng)論 1 5
  • 本文轉(zhuǎn)自 http://www.cnblogs.com/manji/p/4903990.html二叉樹-****你...
    doublej_yjj閱讀 750評(píng)論 0 8
  • 二叉樹-你必須要懂!(二叉樹相關(guān)算法實(shí)現(xiàn)-iOS) http://www.cnblogs.com/manji/p/...
    漢秋閱讀 1,952評(píng)論 0 16
  • 1.什么是二叉樹? 在計(jì)算機(jī)科學(xué)中,二叉樹是每個(gè)節(jié)點(diǎn)最多有兩個(gè)子樹的樹結(jié)構(gòu)。通常子樹被稱作“左子樹”和“右子樹”,...
    zcaaron閱讀 1,355評(píng)論 2 15

友情鏈接更多精彩內(nèi)容