[B003] Tree path the sum of the II (back)

One, Title Description

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]
]

Second, the problem solution

Method One: backtracking

The title on the basis of the sum of the path requires specific method returns qualified path. But routine is the same.

  • End condition :
    • When the leaf nodes traversed, we can determine whether or not the current cumulative sum is equal to cur target.
    • Recursive constantly left subtree, when the end of the left sub-tree recursively, will return near the floor, so where do we go back, the last value path removed.
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);
  }
}

Complexity Analysis

  • time complexity: O ( n ) O (n) ,
  • Space complexity: O ( n ) O (n) ,

Method Two: Optimize

We do not need another inside each method coupled with left, right judgment, replaced by a judgment of the root plus non-empty in the process of beginning.

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);
}

Complexity Analysis

  • time complexity: O ( n ) O (n) ,
  • Space complexity: O ( n ) O (n) ,
Published 495 original articles · won praise 105 · views 30000 +

Guess you like

Origin blog.csdn.net/qq_43539599/article/details/104823248