125、路徑總和III
阿新 • • 發佈:2018-12-31
題目描述:
需要注意的是,樹的節點不一定都是正數,並且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); } }