给出一个算法,判断是否存在路径的数据和等于给定值
思路
递归实现如下步骤,在调用其孩子结点之前,先把sum减去该结点的值,然后在运行过程中检查sum值是否为0
代码
public boolean hasPathSum(int sum){
return hasPathSum(root,sum);
}
boolean hasPathSum(BinaryNode node,int sum){
//如果所有节点已经被访问,并且sum==0,返回true
if(node == null )
return sum == 0;
else{
//检查两颗子树
int subSum = sum - node.getData();
return hasPathSum(node.getRight(),sum) || hasPathSum(node.getLeft(),sum);
}
}