本文共 2140 字,大约阅读时间需要 7 分钟。
1. 先序遍历的思想
正向思路:
public ArrayList> FindPath(TreeNode root, int target) { ArrayList > all = new ArrayList >(); // 先对二叉树的情况进行判断 if (root == null) return all; // 存放每一轮的搜索结果 ArrayList list = new ArrayList (); int sum = 0; dfs(root, target, all, list, sum); return all; } public void dfs(TreeNode root, int target, ArrayList > all, ArrayList list, int sum) { if (root == null) // 树为空 return ; sum += root.val; list.add(root.val); // 搜索到叶节点并且满足题目条件 if (root.left == null && root.right == null && sum == target) { all.add(new ArrayList (list)); list.remove(list.size()-1); // 移除最后一个元素 return; } // 继续遍历左子树 dfs(root.left, target, all, list, sum); // 继续遍历右子树 dfs(root.right, target, all, list, sum); list.remove(list.size()-1); }
public ArrayList> FindPath(TreeNode root, int target) { ArrayList > all = new ArrayList >(); // 先对二叉树的情况进行判断 if (root == null) return all; // 存放每一轮的搜索结果 ArrayList list = new ArrayList (); int sum = 0; dfs(root, target, all, list, sum); return all; } public void dfs(TreeNode root, int target, ArrayList > all, ArrayList list, int sum) { if (root == null) // 树为空 return ; sum += root.val; list.add(root.val); // 搜索到叶节点并且满足题目条件 if (root.left == null && root.right == null && sum == target) { all.add(new ArrayList (list)); } // 继续遍历左子树 if (root.left != null) dfs(root.left, target, all, list, sum); // 继续遍历右子树 if (root.right != null) dfs(root.right, target, all, list, sum); list.remove(list.size()-1); }
另一种思路:
private ArrayList> all = new ArrayList >(); // 存放最终结果 private ArrayList list = new ArrayList (); // 存放每一轮的结果 public ArrayList > FindPath(TreeNode root, int target) { // 先对二叉树的情况进行判断 if (root == null) // 树为空 return all; list.add(root.val); target -= root.val; // 搜索到叶节点并且满足题目条件 if (target == 0 && root.left == null && root.right == null) all.add(new ArrayList<>(list)); // 继续遍历左子树 FindPath(root.left, target); // 继续遍历右子树 FindPath(root.right, target); list.remove(list.size()-1); // 移除最后一个结点(叶子结点) return all ; }