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;