当前位置: 面试刷题>> 二叉树的某层节点之和 (经典算法题500道)
### 题目描述补充
给定一个二叉树,编写一个函数来计算给定深度的所有节点值之和。
**示例**:
给定二叉树:
```
3
/ \
9 20
/ \
15 7
```
- 如果深度为 2,则应返回 9 + 20 = 29。
- 如果深度为 3,则应返回 15 + 7 = 22。
### PHP 示例代码
```php
class TreeNode {
public $val;
public $left;
public $right;
function __construct($val = 0, $left = null, $right = null) {
$this->val = $val;
$this->left = $left;
$this->right = $right;
}
}
function sumOfLevels($root, $depth) {
if ($root == null || $depth <= 0) {
return 0;
}
if ($depth == 1) {
return $root->val;
}
// 递归计算左右子树对应深度的和
return sumOfLevels($root->left, $depth - 1) + sumOfLevels($root->right, $depth - 1);
}
// 示例用法
$root = new TreeNode(3);
$root->left = new TreeNode(9);
$root->right = new TreeNode(20);
$root->right->left = new TreeNode(15);
$root->right->right = new TreeNode(7);
echo sumOfLevels($root, 2); // 输出 29
echo "\n";
echo sumOfLevels($root, 3); // 输出 22
```
### Python 示例代码
```python
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def sumOfLevels(root, depth):
if not root or depth <= 0:
return 0
if depth == 1:
return root.val
return sumOfLevels(root.left, depth - 1) + sumOfLevels(root.right, depth - 1)
# 示例用法
root = TreeNode(3)
root.left = TreeNode(9)
root.right = TreeNode(20)
root.right.left = TreeNode(15)
root.right.right = TreeNode(7)
print(sumOfLevels(root, 2)) # 输出 29
print(sumOfLevels(root, 3)) # 输出 22
```
### JavaScript 示例代码
```javascript
function TreeNode(val, left, right) {
this.val = (val===undefined ? 0 : val)
this.left = (left===undefined ? null : left)
this.right = (right===undefined ? null : right)
}
function sumOfLevels(root, depth) {
if (!root || depth <= 0) {
return 0;
}
if (depth === 1) {
return root.val;
}
return sumOfLevels(root.left, depth - 1) + sumOfLevels(root.right, depth - 1);
}
// 示例用法
const root = new TreeNode(3);
root.left = new TreeNode(9);
root.right = new TreeNode(20);
root.right.left = new TreeNode(15);
root.right.right = new TreeNode(7);
console.log(sumOfLevels(root, 2)); // 输出 29
console.log(sumOfLevels(root, 3)); // 输出 22
```
码小课网站中有更多关于二叉树、递归、深度优先搜索等相关内容分享给大家学习,帮助大家更好地理解和应用这些算法。