同看懂做不出来。。。
class Solution: def pathSum(self, root: TreeNode, sum: int) -> List[List[int]]: res=[] if not root: return [] def helper(root,sum,tmp): if not root: return if not root.left and not root.right and sum-root.val==0: tmp+=[root.val] res.append(tmp) return helper(root.left,sum-root.val,tmp+[root.val]) helper(root.right,sum-root.val,tmp+[root.val]) helper(root,sum,[]) return res
执行用时 :72 ms, 在所有 python3 提交中击败了39.94%的用户
内存消耗 :19.1 MB, 在所有 python3 提交中击败了5.08%的用户
——2019.11.21
复习:
public List<List<Integer>> pathSum(TreeNode root, int sum) { //得用到栈吧 //遍历所有路径 List<List<Integer>> list = new ArrayList<>(); if(root == null){ return list; } Stack<Integer> path = new Stack<>(); pathSum(root,sum,list,path); return list; } private void pathSum(TreeNode node, int sum, List<List<Integer>> list,Stack<Integer> path) { if(node == null && sum != 0){ return; } if(node != null) { if (node.left == null && node.right == null && sum == node.val) { path.push(node.val); list.add(new ArrayList<>(path)); path.pop(); } else { path.push(node.val); pathSum(node.left, sum - node.val, list, path); pathSum(node.right, sum - node.val, list, path); path.pop(); } } }
——2020.7.2