1.给定一个二叉树和一个值sum,请找出是否存在所有的根节点到叶子节点的节点值之和等于sum的路径。
2.给定一个二叉树和一个值sum,请找出所有的根节点到叶子节点的节点值之和等于sum的路径。
<?php
class Node{
public $left = null;
public $right = null;
public $val;
public function __construct($val) {
$this->val = $val;
}
}
//是否有
function hasPathSum($root, $sum) {
if ($root == null) {
return false;
}
if ($root->left == null && $root->right == null) {
if ($sum = $root->val) {
return true;
} else {
return false;
}
}
$bolLeft = hasPathSum($root->left, $sum - $root->val);
$bolRight = hasPathSum($root->right, $sum - $root->val);
return $bolLeft || $bolRight;
}
//所有路径
function pathSum($root, $sum, &$arrOutput = array()) {
if ($root == null) {
return;
}
array_push($arrOutput, $root->val);
if ($root->left == null && $root->right == null && $sum == $root->val) {
print json_encode($arrOutput)."\n";
}
pathSum($root->left, $sum - $root->val, $arrOutput);
pathSum($root->right, $sum - $root->val, $arrOutput);
array_pop($arrOutput);
}
$node1 = new Node(5);
$node2 = new Node(4);
$node3 = new Node(8);
$node4 = new Node(11);
$node5 = new Node(13);
$node6 = new Node(4);
$node7 = new Node(7);
$node8 = new Node(2);
$node9 = new Node(5);
$node10 = new Node(1);
$node1->left = $node2;
$node1->right = $node3;
$node2->left = $node4;
$node2->right = $node5;
$node3->left = $node6;
$node4->left = $node7;
$node4->right = $node8;
$node6->left = $node9;
$node6->right = $node10;
$ret = hasPathSum($node1, 22);
print_r($ret);
pathSum($node1, 22);