最终我还是没做出好的解法。还是看的别人的解法。

即使看了别人的解法,开始还实现错了。

还有很长的路要走。



package com.company;

// https://discuss.leetcode.com/topic/64388/simple-ac-java-solution-dfs
// 比我的方法,好多了。唉。
// 我开始准备DFS,然后在栈里面遍历的,非常复杂。
// 唉,还是思维太局限了。
// 我的第一种解法,还实现错了。直接递归是造成和跳跃。。唉。。差劲

class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}

class Solution {

public int pathSum(TreeNode root, int sum) {
if (root == null) {
return 0;
}

int ret = pathWithRoot(root, sum) + pathSum(root.left, sum) + pathSum(root.right, sum);
return ret;
}
private int pathWithRoot(TreeNode root, int sum) {
if (root == null) {
return 0;
}
int ret = 0;
if (root.val == sum) {
ret++;
}
ret += pathWithRoot(root.left, sum-root.val) + pathWithRoot(root.right, sum-root.val);
return ret;
}
}

public class Main {

public static void main(String[] args) {
// write your code here
System.out.println("Hello");
Solution solution = new Solution();

TreeNode root = new TreeNode(10);
TreeNode root1 = new TreeNode(5);
TreeNode root2 = new TreeNode(-3);
TreeNode root3 = new TreeNode(3);
TreeNode root4 = new TreeNode(2);
TreeNode root5 = new TreeNode(11);
TreeNode root6 = new TreeNode(3);
TreeNode root7 = new TreeNode(-2);
TreeNode root8 = new TreeNode(1);
root.left = root1;
root.right = root2;
root1.left = root3;
root1.right = root4;
root2.right = root5;
root3.left = root6;
root3.right = root7;
root4.right = root8;

int ret = solution.pathSum(root, 8);
System.out.printf("Result is %d\n", ret);

}
}


 

 

下面是写错了的代码。。



package com.company;

// https://discuss.leetcode.com/topic/64388/simple-ac-java-solution-dfs
// 比我的方法,好多了。唉。
// 我开始准备DFS,然后在栈里面遍历的,非常复杂。
// 唉,还是思维太局限了。
// 我的第一种解法,还实现错了。直接递归是造成和跳跃。。唉。。差劲

class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}

class Solution {

public int pathSum(TreeNode root, int sum) {
if (root == null) {
return 0;
}
int ret = 0;
if (root.val == sum) {
ret++;
}
ret += pathSum(root.left, sum)
+ pathSum(root.left, sum-root.val)
+ pathSum(root.right, sum)
+ pathSum(root.right, sum-root.val);
System.out.printf("root %d, ret %d, sum %d\n", root.val, ret, sum);
return ret;
}
}

public class Main {

public static void main(String[] args) {
// write your code here
System.out.println("Hello");
Solution solution = new Solution();

TreeNode root = new TreeNode(10);
TreeNode root1 = new TreeNode(5);
TreeNode root2 = new TreeNode(-3);
TreeNode root3 = new TreeNode(3);
TreeNode root4 = new TreeNode(2);
TreeNode root5 = new TreeNode(11);
TreeNode root6 = new TreeNode(3);
TreeNode root7 = new TreeNode(-2);
TreeNode root8 = new TreeNode(1);
root.left = root1;
root.right = root2;
root1.left = root3;
root1.right = root4;
root2.right = root5;
root3.left = root6;
root3.right = root7;
root4.right = root8;

int ret = solution.pathSum(root, 8);
System.out.printf("Result is %d\n", ret);

}
}