【樹】B003 路徑總和 II(回溯)

一、題目描述

Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.

Note: A leaf is a node with no children.

Given the below binary tree and sum = 22,
      5
     / \
    4   8
   /   / \
  11  13  4
 /  \    / \
7    2  5   1
Return:
[
   [5,4,11,2],
   [5,8,4,5]
]

二、題解

方法一:回溯

本題在路徑總和的基礎之上要求方法返回符合條件的具體路徑。但套路都是一樣。

  • 結束條件
    • 當遍歷到葉子結點,我們可以判斷當前累加和 cur 是否等於 target。
    • 不斷遞歸左子樹,當左子樹遞歸結束,一定會返回臨近的上一層,所以在這裏我們做回溯,將 path 的最後一個值去掉。
List<List<Integer>> paths = null;
List<Integer> path = null;
int sum = 0;
public List<List<Integer>> pathSum(TreeNode root, int target) {
  paths = new LinkedList<>();
  if (root == null)
      return paths;
  path = new ArrayList<>();
  sum = target;
  dfs(root, root.val);
  return paths;
}
private void dfs(TreeNode root, int cur) {
  path.add(root.val);
  if (root.left == null && root.right == null && cur == sum) {
      paths.add(new ArrayList<>(path));
      return;
  }
  if (root.left != null) {
      dfs(root.left, cur + root.left.val);
      path.remove(path.size() - 1);
  }
  if (root.right != null) {
      dfs(root.right, cur + root.right.val);
      path.remove(path.size() - 1);
  }
}

複雜度分析

  • 時間複雜度:O(n)O(n)
  • 空間複雜度:O(n)O(n)

方法二:優化

我們沒必要再每一個方法裏面加上對 left,right 的判斷,取而代之的是在方法開頭處加上對 root 的非空判斷。

List<List<Integer>> paths = null;
List<Integer> path = null;
public List<List<Integer>> pathSum(TreeNode root, int sum) {
  paths = new LinkedList<>();
  path = new ArrayList<>();
  dfs(root, sum);
  return paths;
}
private void dfs(TreeNode root, int re) {
  if (root == null) {
      return;
  }
  path.add(root.val);
  if (root.left == null && root.right == null && re == root.val) {
      paths.add(new ArrayList<>(path));
      path.remove(path.size()-1);
      return;
  }
  dfs(root.left, re - root.val);
  dfs(root.right, re - root.val);
  path.remove(path.size()-1);
}

複雜度分析

  • 時間複雜度:O(n)O(n)
  • 空間複雜度:O(n)O(n)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章