题目描述:
需要注意的是,树的节点不一定都是正数,并且target也不一定是正数,意思就是当你只有执行到叶子节点时才能结束,否则还需要继续
代码
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public static int count = 0;
public static int pathSum(TreeNode root, int sum) {
if(root == null){
return 0;
}
if(root.left == null && root.right == null){
if(root.val != sum){
return 0;
}else {
return 1;
}
}
Stack<TreeNode> tem = new Stack<>();
tem.push(root);
while (!tem.isEmpty()) {
TreeNode s = tem.pop();
find(s,sum,0);
if(s.left != null){
tem.push(s.left);
}
if(s.right != null){
tem.push(s.right);
}
}
return Solution.count;
}
public static void find(TreeNode treeNode,int exceptsum,int currentnum){
if(treeNode.val + currentnum == exceptsum){
Solution.count++;
}
if(treeNode.left != null){
find(treeNode.left,exceptsum, currentnum + treeNode.val);
}
if(treeNode.right != null){
find(treeNode.right,exceptsum, currentnum + treeNode.val);
}
}
}
奇怪的时同样的测试用例运行没问题,提交就出问题。。。
排名靠前的代码
class Solution {
int path = 0;
public int pathSum(TreeNode root, int sum) {
path_sum(root,sum,new int[0]);
return path;
}
public void path_sum(TreeNode node, int sum,int[] array){
if(node == null) return ;
int[] newArray= new int[array.length+1];
for(int i = 0 ;i<array.length;i++){
newArray[i] = array[i]+node.val;
if(newArray[i] == sum) path+=1;
}
newArray[array.length] = node.val;
if(node.val == sum) path+=1;
if(node.left!=null) path_sum(node.left, sum, newArray);
if(node.right!=null) path_sum(node.right, sum, newArray);
}
}