[B003] Tree path the sum of the I - III (Template Summary)

Root of the problem: starting from the root to some of the path to see if there is a junction point of the sum of the weights for the sum of.

Code Templates

if (root 为空) 
	return false;
if (叶子结点 或 其他条件)   
	return re == root.val;
return 左子树 || 右子树...

The sum of the path I

private boolean dfs(TreeNode root, int re) {
  if (root == null) {
    return false;
  }
  if (root.left == null && root.right == null) {
    return re  == root.val;
  }
  return dfs(root.left, re-root.val) || dfs(root.right, re-root.val);
}

The sum of the path II

Find All the root-to-Leaf Paths WHERE each path the equals apos SUM GIVEN The SUM, obtaining specific path. Related to the path, we need to be saved node traversal encountered in the process, when finding a legitimate path, we should go back to the previous step (a node), continue to change the direction of the search.

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

Total Path III

Found in the tree for the path sum sum, the beginning of the path may not be the root node, it may not be the end of the leaf nodes. So we can not let any one node as the beginning of the path.

This problem can be recursively dual . However, two-way means that there are many repeat traversal.

public int pathSum(TreeNode root, int sum) {
  if (root == null)
      return 0;
  dfs(root, sum);
  pathSum(root.left, sum);
  pathSum(root.right, sum);
  return cnt;
}
void dfs(TreeNode root, int re) {
  if (root == null) {
      return;
  }
  if (re == root.val) {
      cnt++;
  }
  dfs(root.left, re-root.val);
  dfs(root.right, re-root.val);
}
Published 495 original articles · won praise 105 · views 30000 +

Guess you like

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