題目描述:輸入一棵二叉樹的根節點,求該樹的深度。從根節點到葉節點依次經過的節點(含根、葉節點)形成樹的一條路徑,最長路徑的長度爲樹的深度。
解法 1: 遞歸
遞歸的寫法非常直觀。對於一棵二叉樹來說,它的高度等於左右子樹的高度最大值,加上 1。
代碼實現如下:
// ac地址:https://leetcode-cn.com/problems/maximum-depth-of-binary-tree/
// 原文地址:https://xxoo521.com/2020-03-22-max-depth/
/**
* @param {TreeNode} root
* @return {number}
*/
var maxDepth = function(root) {
if (!root) return 0;
return 1 + Math.max(maxDepth(root.left), maxDepth(root.right));
};
解法 2: 層序遍歷
按照二叉樹的“層”去遍歷,最後返回層的數目。這題和《劍指 offer - 從上到下打印二叉樹 III - JavaScript》思路完全一樣。
細節請看代碼註釋,代碼實現如下:
// ac地址:https://leetcode-cn.com/problems/maximum-depth-of-binary-tree/
// 原文地址:https://xxoo521.com/2020-03-22-max-depth/
/**
* @param {TreeNode} root
* @return {number}
*/
var maxDepth = function(root) {
if (!root) return 0;
let res = 0;
const queue = [root];
while (queue.length) {
let levelNum = queue.length; // 當前層中二叉樹的節點數量
++res;
// 依次將下一層的二叉樹節點放入隊列
while (levelNum--) {
const node = queue.shift();
if (node.left) queue.push(node.left);
if (node.right) queue.push(node.right);
}
}
return res;
};
更多資料
整理不易,若對您有幫助,請給個「關注+點贊」,您的支持是我更新的動力 👇
- 📖Blog:劍指 Offer 題解 + JS 代碼
- 🐱Github :https://github.com/dongyuanxin/blog
- 🌟 公衆號:心譚博客