January 11, 2024

Viiisit [LeetCode] - 104. Maximum Depth of Binary Tree

#php#javascript#ruby

keep learning, keep coding!

Problem - Maximum Depth of Binary Tree

Given the root of a binary tree, return its maximum depth.

A binary tree’s maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

翻譯蒟蒻

計算二元樹的最大深度。


使用遞迴方式來找出二元樹的最大深度。


Solution - JavaScript

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @return {number}
*/
var maxDepth = function(root) {
if (root === null) {
return 0;
}
let left = maxDepth(root.left);
let right = maxDepth(root.right);
return Math.max(left, right) + 1;
};

Solution - Ruby

1
2
3
4
5
6
def max_depth(root)
return 0 if root.nil?
left = max_depth(root.left)
right = max_depth(root.right)
return 1 + [left, right].max
end

Solution - PHP

1
2
3
4
5
6
7
function maxDepth($root) {
if ($root === null) return 0;

$left = $this->maxDepth($root->left);
$right = $this->maxDepth($root->right);
return max($left, $right) + 1;
}

LeetCode 傳送門 - Maximum Depth of Binary Tree