package niuke.day1;
import java.util.Stack;
/*Given a binary tree and a sum, determine if the tree has a root-to-leaf path such
that adding up all the values along the path equals the given sum.
For example:
Given the below binary tree andsum = 22,
5
/ \
4 8
/ / \
11 13 4
/ \ \
7 2 1
return true, as there exist a root-to-leaf path5->4->11->2which sum is 22. */
//其实本题并没有重复的子问题,无需考虑动态规划,单纯的递归完全可以解决问题
public class Path_Sum {
public static void main(String[] args) {
TreeNode t1 = new TreeNode(1);
TreeNode t2 = new TreeNode(2);
t1.right = t2;
System.out.println(hasPathSum(t1, 3));
}
static Stack<TreeNode> s = new Stack<>(); //本题利用栈替代了递归的过程,事实证明我还是不擅长递归
static boolean flag = false; //定义标志位
public static boolean hasPathSum(TreeNode root, int sum) {
if(root != null)
s.push(root);
while(!s.isEmpty() && flag != true) { //当栈不为空或者还没有找到符合条件的路径则一直循环
TreeNode temp = s.pop();
if(temp.val == sum && temp.left == null && temp.right == null) {
flag = true; //正好是叶子节点,又恰好满足条件则修改标志位
}
if(temp.left != null ) {
temp.left.val += temp.val;
hasPathSum(temp.left, sum);//当左子树不为空的时候则继续调用自己
}
if(temp.right != null ) {
temp.right.val += temp.val;
hasPathSum(temp.right, sum);
}
}
return flag;
//以下是来自网友的另一种解法
/*public boolean hasPathSum(TreeNode root, int sum) {
if(root==null){
return false; //我常犯的错误就是把递归里的返回值理解为是整体的返回,其实这只是递归的一步返回
}
if(root.left==null &&root.right==null){//当是叶子节点的时候
if(sum-root.val==0){
return true; //如果满足结果则返回true
}else{
return false; //否则就返回false
}
}
boolean left=hasPathSum(root.left,sum-root.val); //理解的重点,不断的递归
boolean right=hasPathSum(root.right,sum-root.val);
return left||right;//当左子树满足或者右子树满足都可以,当底层的树满.足会不断的返回,直到返回最上层,还是要深入理解递归的思路
}*/
}
}