王廷瑋|數位醫療|智慧醫療: 104. Maximum Depth of Binary Tree WFU

2024年7月5日 星期五

104. Maximum Depth of Binary Tree

104. Maximum Depth of Binary Tree


給定一個二元樹的根節點,返回其最大深度。

二元樹的最大深度是從根節點到最遠葉節點的最長路徑上的節點數。

範例:

輸入:root = [3,9,20,null,null,15,7] 輸出:3

這表明二元樹的最大深度是3,因為從根節點3到最遠的葉節點(15或7)共有3個節點。


Python


# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right

class Solution:
def maxDepth(self, root: Optional[TreeNode]) -> int:
# Base case: if the tree is empty, the depth is 0
if root is None:
return 0
# Recursively find the depth of the left and right subtrees
left_depth = self.maxDepth(root.left)
right_depth = self.maxDepth(root.right)
# The depth of the tree is the greater of the two depths plus 1 for the root node
return max(left_depth, right_depth) + 1

17.58MB, 37ms


C++


/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/

class Solution {
public:
int maxDepth(TreeNode* root) {
// Base case: if the tree is empty, the depth is 0
if (root == nullptr) {
return 0;
}
// Recursively find the depth of the left and right subtrees
int leftDepth = maxDepth(root->left);
int rightDepth = maxDepth(root->right);
// The depth of the tree is the greater of the two depths plus 1 for the root node
return std::max(leftDepth, rightDepth) + 1;
}
};

17.4MB, 7ms


Javascript


/**
* 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) {
// Base case: if the root is null, the depth is 0
if (root === null) {
return 0;
}
// Recursively find the depth of the left and right subtrees
const leftDepth = maxDepth(root.left);
const rightDepth = maxDepth(root.right);
// The depth of the tree is the greater of the two depths plus 1 for the root node
return Math.max(leftDepth, rightDepth) + 1;
};

51.24MB, 57ms