当前位置: 面试刷题>> 二叉树叶子节点之和 (经典算法题500道)
### 题目描述
给定一棵二叉树,请计算这棵二叉树中所有叶子节点的值之和。叶子节点是指没有子节点的节点。
### 示例
假设有以下二叉树:
```
3
/ \
9 20
/ \
15 7
```
这棵二叉树的叶子节点是 9、15 和 7,它们的和是 31。
### PHP 示例代码
```php
val = $val;
$this->left = $left;
$this->right = $right;
}
}
function sumOfLeafNodes($root) {
if ($root === null) {
return 0;
}
if ($root->left === null && $root->right === null) {
// 叶子节点
return $root->val;
}
// 递归计算左右子树叶子节点之和
return sumOfLeafNodes($root->left) + sumOfLeafNodes($root->right);
}
// 示例用法
$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 sumOfLeafNodes($root); // 输出 31
?>
```
### Python 示例代码
```python
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def sumOfLeafNodes(root):
if not root:
return 0
if not root.left and not root.right:
# 叶子节点
return root.val
# 递归计算左右子树叶子节点之和
return sumOfLeafNodes(root.left) + sumOfLeafNodes(root.right)
# 示例用法
root = TreeNode(3)
root.left = TreeNode(9)
root.right = TreeNode(20)
root.right.left = TreeNode(15)
root.right.right = TreeNode(7)
print(sumOfLeafNodes(root)) # 输出 31
```
### 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 sumOfLeafNodes(root) {
if (!root) {
return 0;
}
if (!root.left && !root.right) {
// 叶子节点
return root.val;
}
// 递归计算左右子树叶子节点之和
return sumOfLeafNodes(root.left) + sumOfLeafNodes(root.right);
}
// 示例用法
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(sumOfLeafNodes(root)); // 输出 31
```
码小课网站中有更多相关内容分享给大家学习,包括但不限于算法题解、数据结构、编程技巧等,欢迎访问学习。