判断树的路径数据和等于给定值

给出一个算法,判断是否存在路径的数据和等于给定值

思路

递归实现如下步骤,在调用其孩子结点之前,先把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);	
  }
}

猜你喜欢

转载自blog.csdn.net/weixin_37632716/article/details/114379155