《leetcode-php》二叉树从根到叶组成的数求和

本文探讨了如何在二叉树中寻找所有从根节点到叶子节点的路径,并计算这些路径所代表数字的总和。通过递归算法,每向下一层,路径数更新为上一层的10倍加上当前节点值,最终返回左子树和右子树路径和的总和。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Given a binary tree containing digits from0-9only, each root-to-leaf path could represent a number.
An example is the root-to-leaf path1->2->3which represents the number123.
Find the total sum of all root-to-leaf numbers.
For example,
1
/ \
2   3

The root-to-leaf path1->2represents the number12.
The root-to-leaf path1->3represents the number13.
Return the sum = 12 + 13 =25.
从根到叶组成所有数求和。

思路:
每向下一层,都是 上面的和*10+当前值 作为组成的数。

分叉的情况就是 左边+右边

<?php
class TreeNode {
    public $val;
    public $left  = null;
    public $right = null;
    public function __construct($val) {
        $this->val = $val;
    }
}
function sumNumbers($head, $ret) {
    if ($head->left == null && $head->right == null) {
        return $ret * 10 + $head->val;
    }
    $leftRet  = 0;
    $rightRet = 0;
    if ($head->left !== null) {
        $leftRet = sumNumbers($head->left, $ret * 10 + $head->val);
    }
    if ($head->right !== null) {
        $rightRet = sumNumbers($head->right, $ret * 10 + $head->val);
    }
    return $leftRet + $rightRet;
}
$node1 = new TreeNode(1);
$node2 = new TreeNode(2);
$node3 = new TreeNode(3);
$node4 = new TreeNode(4);
$node1->left  = $node2;
$node1->right = $node3;
$node3->right = $node4;
$ret = sumNumbers($node1, 0);
print $ret;

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值