当前位置: 面试刷题>> 左叶子的和 (经典算法题500道)


题目描述补充

题目:左叶子的和

给定一棵二叉树,我们需要找到所有左叶子节点的和。左叶子节点是指那些没有右子节点的叶子节点。

示例

考虑以下二叉树:

    3
   / \
  9  20
    /  \
   15   7

在这个例子中,左叶子节点是 915,所以返回的结果是 24

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 sumOfLeftLeaves($root) {
    if ($root === null) {
        return 0;
    }
    
    $sum = 0;
    if ($root->left !== null && $root->left->left === null && $root->left->right === null) {
        $sum += $root->left->val;
    }
    
    $sum += sumOfLeftLeaves($root->left);
    $sum += sumOfLeftLeaves($root->right); // 注意,右子树也可能有左叶子节点
    
    return $sum;
}

// 示例用法
$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 sumOfLeftLeaves($root); // 输出 24

Python 示例代码

class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

def sumOfLeftLeaves(root):
    if not root:
        return 0
    
    sum_ = 0
    if root.left and not root.left.left and not root.left.right:
        sum_ += root.left.val
    
    sum_ += sumOfLeftLeaves(root.left)
    sum_ += sumOfLeftLeaves(root.right)
    
    return sum_

# 示例用法
root = TreeNode(3)
root.left = TreeNode(9)
root.right = TreeNode(20)
root.right.left = TreeNode(15)
root.right.right = TreeNode(7)

print(sumOfLeftLeaves(root))  # 输出 24

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 sumOfLeftLeaves(root) {
    if (!root) {
        return 0;
    }
    
    let sum = 0;
    if (root.left && !root.left.left && !root.left.right) {
        sum += root.left.val;
    }
    
    sum += sumOfLeftLeaves(root.left);
    sum += sumOfLeftLeaves(root.right);
    
    return sum;
}

// 示例用法
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(sumOfLeftLeaves(root)); // 输出 24

码小课网站中有更多相关内容分享给大家学习,包含但不限于数据结构、算法、面试技巧等,希望大家能够从中受益,不断提升自己的编程能力。

推荐面试题