二叉树路径求和问题描述
二叉树路径求和问题:
给定一个二叉树的根节点及一个整数目标值,需要找出并打印出所有节点值之和等于该目标值的路径。所谓路径,是指从树的根节点出发,沿着父子关系向下延伸至某个叶节点所经过的所有节点构成的序列。(注意:在返回的结果列表中,包含更多节点的路径数组应排在前面)
解题思路分析:
首先采用二叉树的前序遍历方式,按照“中-左-右”的顺序访问节点。
在递归过程中,将当前的目标值减去当前节点的值,并将更新后的目标值传递给子节点。
当目标值变为0,且当前节点的左右子节点均为空时,说明已到达叶节点且路径和满足条件。
在函数外部维护两个数组:list用于存储当前正在探索的一条路径,listAll用于累积所有满足条件的完整路径。
FindPath(root,target)
if root==null return listAll
list[]=root.val
target-=root.val
if target==0 && root->left==null && root->right==null
listAll[]=list
FindPath(root->left,target)
FindPath(root->right,target)
//如果到了这条路径的跟结点,并没有达到目标,就删掉最后的结点,退回上一个结点
array_pop(list)
return listAll
<?php
class TreeNode{
var $val;
var $left = NULL;
var $right = NULL;
function __construct($val){
$this->val = $val;
}
}
function FindPath($root,$target)
{
static $list=array();
static $listAll=array();
if($root==null){
return $listAll;
}
$target-=$root->val;
$list[]=$root->val;
if($target==0 && $root->left==null && $root->right==null){
$listAll[]=$list;
}
FindPath($root->left,$target);
FindPath($root->right,$target);
array_pop($list);
return $listAll;
}
$node10=new TreeNode(10);
$node5=new TreeNode(5);
$node12=new TreeNode(12);
$node4=new TreeNode(4);
$node7=new TreeNode(7);
$node10->left=$node5;
$node10->right=$node12;
$node5->left=$node4;
$node5->left=$node7;
$tree=$node10;
$res=FindPath($tree,22);
var_dump($res);
<?php
/*class TreeNode{
var $val;
var $left = NULL;
var $right = NULL;
function __construct($val){
$this->val = $val;
}
}*/
function FindPath($root,$target)
{
$list=array();
$listAll=array();
$res=dfs($root,$target,$list,$listAll);
return $res;
}
function dfs($root,$target,&$list,&$listAll)
{
if($root==null){
return $listAll;
}
$target-=$root->val;
$list[]=$root->val;
if($target==0 && $root->left==null && $root->right==null){
$listAll[]=$list;
}
dfs($root->left,$target,$list,$listAll);
dfs($root->right,$target,$list,$listAll);
array_pop($list);
return $listAll;
}
以上即为本次分享的全部实例代码,读者可自行进行测试验证,感谢大家对本站的支持。