Leecode no.112 路径总和

package tree;

/**
* 112.路径总和
*
* 给你二叉树的根节点 root 和一个表示目标和的整数 targetSum ,判断该树中是否存在 根节点到叶子节点 的路径,这条路径上所有节点值相加等于目标和 targetSum 。
*
* @author Tang
* @date 2021/7/16
*/
public class HasPathSum {

int targetSum;

boolean flag = false;

public boolean hasPathSum(TreeNode root, int targetSum) {
if(root == null){
return false;
}
this.targetSum = targetSum;
preSearch(root, 0);
return flag;
}

/**
* 一个前序遍历搞定
*/
private void preSearch(TreeNode node, int val){
if(node == null){
return;
}
val += node.val;
if(node.left == null && node.right == null){
if(val == targetSum){
flag = true;
}
}
preSearch(node.left, val);
preSearch(node.right, val);
}


public static void main(String[] args) {

}


}
原文地址:https://www.cnblogs.com/ttaall/p/15019997.html