Path Sum II

https://leetcode.com/problems/path-sum-ii/

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

Thoughts

DFS整棵树.

Code

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    private void dfs(TreeNode node, int residual, List<Integer> path, List<List<Integer>> res) {
        if (node == null) {
            return;
        }

        path.add(node.val);
        residual -= node.val;
        if (node.left == null && node.right == null && residual == 0) {
            res.add(new ArrayList<>(path));
        } 

        dfs(node.left, residual, path, res);
        dfs(node.right, residual, path, res);

        residual += node.val;
        path.remove(path.size() - 1);
    }

    public List<List<Integer>> pathSum(TreeNode root, int sum) {
        List<List<Integer>> res = new ArrayList<>();
        dfs(root, sum, new ArrayList<>(), res);
        return res;
    }
}

Analysis

Errors:

  1. 当是叶子节点且应该加入res忘了把最后一个结点加入path.

每个结点都会被访问,时间复杂度O(n), n为结点数。

Ver. 2

https://discuss.leetcode.com/topic/31698/java-solution-iterative-and-recursive

看着和inorder很像, 区别在于当退回到中间节点时, 不能直接pop, 否则path将不再包含它, 而是要检查它的右子树是否存在, 并把右子树pushLeft. 但如果每次都pushLeft则无法正常让中间节点退出, 因此还要把上个退出的节点记下来, 看是否和中间节点的right一致, 当一致时意味着右子树已经查过了, 不需要再pushLeft了.

Last updated

Was this helpful?