LeetCode113. 路徑總和 II
阿新 • • 發佈:2020-12-24
本題相似題目:LeetCode257. 二叉樹的所有路徑
☆☆☆☆☆方法1:DFS前序遍歷 + 回溯
☆☆方法2:BFS層序遍歷。
☆☆☆方法3:遞迴
程式碼1:DFS前序遍歷 + 回溯(耗時1ms)
class Solution { public List<List<Integer>> pathSum(TreeNode root, int sum) { List<List<Integer>> res = new ArrayList<>(); dfs1(root,new ArrayList<>(), res, sum); // dfs2(root, new ArrayList<>(), res, 0, sum); return res; } // 回溯 往下減 private void dfs1(TreeNode root, List<Integer> list, List<List<Integer>> res, int target) { if (root == null) return; list.add(root.val);if (target == root.val && root.left == null && root.right == null) { res.add(new ArrayList<>(list)); list.remove(list.size() - 1); // 注意,此處return前也需要重置 return; } dfs1(root.left, list, res, target - root.val); dfs1(root.right, list, res, target- root.val); list.remove(list.size() - 1); // 遞迴呼叫某一節點的左右孩子之後,再移除這個節點。 } // 回溯 往下加 private void dfs2(TreeNode root, List<Integer> list, List<List<Integer>> res, int temp, int target) { if (root == null) return; list.add(root.val); temp += root.val; if (temp == target && root.left == null && root.right == null) { res.add(new ArrayList<>(list)); list.remove(list.size() - 1); return; } dfs2(root.left, list, res, temp, target); dfs2(root.right, list, res, temp, target); list.remove(list.size() - 1); } }
程式碼2:BFS層序遍歷(耗時4ms)
class Solution { public List<List<Integer>> pathSum(TreeNode root, int sum) { List<List<Integer>> res = new ArrayList<>(); if (root == null) return res; Queue<TreeNode> nodeQueue = new LinkedList<>(); Queue<List<Integer>> pathQueue = new LinkedList<>(); nodeQueue.offer(root); List<Integer> list = new ArrayList<>(); list.add(root.val); pathQueue.offer(list); while (!nodeQueue.isEmpty()) { TreeNode cur = nodeQueue.poll(); List<Integer> path = pathQueue.poll(); if (cur.left == null && cur.right == null) { if (cur.val == sum) { res.add(path); } } if (cur.left != null) { nodeQueue.offer(cur.left); List<Integer> left = new ArrayList<>(path); left.add(cur.left.val); pathQueue.offer(left); cur.left.val += cur.val; // 累加節點的值並修改 } if (cur.right != null) { nodeQueue.offer(cur.right); List<Integer> right = new ArrayList<>(path); right.add(cur.right.val); pathQueue.offer(right); cur.right.val += cur.val; // 累加節點的值並修改 } } return res; } }
程式碼3:遞迴(耗時1ms)
class Solution { public List<List<Integer>> pathSum(TreeNode root, int sum) { List<List<Integer>> res = new ArrayList<>(); if (root == null) return res; if (root.val == sum && root.left == null && root.right == null) { List<Integer> list = new LinkedList<>(); // LinkedList更適合 插入操作 list.add(root.val); res.add(list); return res; } List<List<Integer>> left = pathSum(root.left, sum - root.val); for (List<Integer> l : left) { l.add(0, root.val); res.add(l); // 不要忘了 } List<List<Integer>> right = pathSum(root.right, sum - root.val); for (List<Integer> r : right) { r.add(0, root.val); res.add(r); // 不要忘了 } return res; } }