113_路径总和II
113_路径总和II
package 二叉树.BT; import java.util.ArrayList; import java.util.Collections; import java.util.Deque; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Queue; /** * https://leetcode-cn.com/problems/path-sum-ii/ * @author Huangyujun * */ public class _113_路径总和II { class Solution { List<List<Integer>> ret = new LinkedList<List<Integer>>(); Deque<Integer> path = new LinkedList<Integer>(); public List<List<Integer>> pathSum(TreeNode root, int targetSum) { dfs(root, targetSum); return ret; } public void dfs(TreeNode root, int targetSum) { if (root == null) { return; } path.offerLast(root.val); targetSum -= root.val; if (root.left == null && root.right == null && targetSum == 0) { ret.add(new LinkedList<Integer>(path)); } dfs(root.left, targetSum);// 先到这里的话是叶子结点【可能是叶子(左边已经遍历完)】 dfs(root.right, targetSum);// 然后叶子结点的右边 path.pollLast(); // 这里poll掉我有疑惑???-------右边遍历完,必然是叶子 } } /** * [可能是使用了map 集合,效率很低哈哈哈哈] * 思路分析: * map 结合【键:当前结点, 值:父结点】 * 队列queueSum 是计算路径的值【将计算过结果放到栈顶】,stack 遍历结点的栈 * @author Huangyujun * */ class Solution2 { List<List<Integer>> ret = new LinkedList<List<Integer>>(); Map<TreeNode, TreeNode> map = new HashMap<TreeNode, TreeNode>(); public List<List<Integer>> pathSum(TreeNode root, int targetSum) { if (root == null) { return ret; } Queue<TreeNode> stack = new LinkedList<TreeNode>(); Queue<Integer> queueSum = new LinkedList<Integer>(); stack.offer(root); queueSum.offer(0); while (!stack.isEmpty()) { TreeNode node = stack.poll(); int rec = queueSum.poll() + node.val; if (node.left == null && node.right == null) { if (rec == targetSum) { getPath(node); } } else { if (node.left != null) { map.put(node.left, node); stack.offer(node.left); queueSum.offer(rec); } if (node.right != null) { map.put(node.right, node); stack.offer(node.right); queueSum.offer(rec); } } } return ret; } public void getPath(TreeNode node) { List<Integer> temp = new LinkedList<Integer>(); while (node != null) { temp.add(node.val); node = map.get(node); } Collections.reverse(temp); ret.add(new LinkedList<Integer>(temp)); } } /** * 思路不对,我只想明白了左到尽头不一定是叶子的bug *后边进行判断了,为啥还是bug * * @param root * @param targetSum * @return */ public List<List<Integer>> pathSum(TreeNode root, int targetSum) { List<Integer> item = new LinkedList<>(); List<List<Integer>> res = new LinkedList<>(); Deque<TreeNode> stack = new LinkedList<>(); TreeNode node = root; int num = 0; while (node != null || !stack.isEmpty()) { while (node != null) { item.add(node.val); num += node.val; stack.push(node); node = node.left; } // 左到尽头,不是叶子,可能度为1【需要进行判断】 // 判断一下 if (stack.peek().right == null) { if (num == targetSum) { res.add(item); } // 到达叶子了 int temp = ((Deque<Integer>) item).pollLast(); num -= temp; } // 吐掉当前结点 node = stack.pop(); node = node.right; } return res; } }
本文来自博客园,作者:一乐乐,转载请注明原文链接:https://www.cnblogs.com/shan333/p/15709221.html