437 Path Sum III

You are given a binary tree in which each node contains an integer value.
Find the number of paths that sum to a given value.
The path does not need to start or end at the root or a leaf, but it must go downwards (traveling only from parent nodes to child nodes).
The tree has no more than 1,000 nodes and the values are in the range -1,000,000 to 1,000,000.

Example:

root = [10,5,-3,3,2,null,11,3,-2,null,1], sum = 8
Return 3. The paths that sum to 8 are:

  1. 5 -> 3
  2. 5 -> 2 -> 1
  3. -3 -> 11

解释下题目:

给定一棵树,找到其中任意一条路径使得它们的和是指定的数字,这条路径不一定非要从根节点到叶子节点。

1. DFS遍历

实际耗时:9ms

private int count = 0;

    public int pathSum(TreeNode root, int sum) {
        if (root == null) {
            return 0;
        }
        helper(root, sum, 0);
        //以下两句是关键
        pathSum(root.left, sum);
        pathSum(root.right, sum);
        return count;
    }

    private void helper(TreeNode root, int sum, int cur) {
        if (root == null) {
            return;
        }
        cur += root.val;
        if (cur == sum) {
            count++;
        }
        if (root.left != null) {
            helper(root.left, sum, cur);
        }
        if (root.right != null) {
            helper(root.right, sum, cur);
        }
    }

  其实一开始我拿到这道题目的时候想的是DFS,但是感觉是不是太简单了点,有没有更简单的方法,就去找规律,但是遗憾的发现有负数,说明只能老老实实的遍历,所以时间复杂度其实很高

时间复杂度O(n^2)
空间复杂度O(1)

你可能感兴趣的:(437 Path Sum III)