Time:2019/4/22
Title: Maximum Depth of Binary Tree
Difficulty: Medium
Author:小鹿
javascript
Given a binary tree, find its maximum depth.java
The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.node
給定一個二叉樹,找出其最大深度。git
二叉樹的深度爲根節點到最遠葉子節點的最長路徑上的節點數。github
說明: 葉子節點是指沒有子節點的節點。算法
Note: A leaf is a node with no children.編程
Example:bash
Given binary tree [3,9,20,null,null,15,7]
,ui
3
/ \
9 20
/ \
15 7
複製代碼
return its depth = 3.spa
求二叉樹的最大深度,咱們要知道樹的深度怎麼計算的?
1)樹的深度,深度,顧名思義,從上到下,第一層爲 1,每向下一層,深度 + 1。
2)觀察上圖,咱們計算時,只需記錄兩個子樹最深的結點爲主。
3)求二叉樹的深度,必然要用到遞歸來解決。
1)判斷樹是否爲 null。
2)分別遞歸左右子樹。
3)只計算疊加計數(遞歸最深)最大的數字。
var maxDepth = function(root) {
// 若是根節點爲 null
if(root === null) return 0;
// 遞歸左子樹
let depthLeft = maxDepth(root.left);
// 遞歸右子樹
let depthRight = maxDepth(root.right);
// 將子問題合併求總問題
return Math.max(depthLeft,depthRight) + 1;
};
複製代碼
歡迎一塊兒加入到 LeetCode 開源 Github 倉庫,能夠向 me 提交您其餘語言的代碼。在倉庫上堅持和小夥伴們一塊兒打卡,共同完善咱們的開源小倉庫! Github:https://github.com/luxiangqiang/JS-LeetCode 歡迎關注我我的公衆號:「一個不甘平凡的碼農」,記錄了本身一路自學編程的故事。