当前位置: 面试刷题>> 叶节点的和 (经典算法题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 ``` **码小课**网站中有更多相关内容分享给大家学习,包括但不限于算法基础、数据结构、面试题解析等,欢迎访问学习。