劍#指 Offer 34. 二叉樹中和為某一值的路徑
阿新 • • 發佈:2022-03-19
劍指 Offer 34. 二叉樹中和為某一值的路徑
List不能只增加介面 必須實現類Arraylist or linkedlist
給你二叉樹的根節點 root 和一個整數目標和 targetSum ,找出所有 從根節點到葉子節點 路徑總和等於給定目標和的路徑。
葉子節點 是指沒有子節點的節點。
示例 1:
輸入:root = [5,4,8,11,null,13,4,7,2,null,null,5,1], targetSum = 22
輸出:[[5,4,11,2],[5,8,4,5]]
示例 2:
輸入:root = [1,2,3], targetSum = 5
輸出:[]
示例 3:
輸入:root = [1,2], targetSum = 0
輸出:[]
提示:
樹中節點總數在範圍 [0, 5000] 內
-1000 <= Node.val <= 1000
-1000 <= targetSum <= 1000
注意:本題與主站 113 題相同:https://leetcode-cn.com/problems/path-sum-ii/
通過次數174,933提交次數299,751
class Solution { List<List<Integer>> res =new ArrayList<>(); public List<List<Integer>> pathSum(TreeNode root, int target) { List<Integer> list = new ArrayList<>(); path(0,root,target,list); return res; } public void path(int sum ,TreeNode root, int target,List<Integer> list) { if(root==null) { return; } sum+=root.val; //5+ 4+11+2 System.out.println(sum); System.out.println(root.val); list.add(root.val); if(sum==target&&root.left==null&&root.right==null) { System.out.println("root is null "); res.add(new LinkedList<Integer>(list));//加介面沒有答案 } path(sum,root.left,target,list); path(sum,root.right,target,list); list.remove(list.size()-1); //把不符合題意的葉子節點直接移除。 } }