Path Sum

Given a binary tree and a sum, determine if the tree has a
root-to-leaf path such that adding up all the values along the path
equals the given sum.

For example: Given the below binary tree and sum = 22,

          5
         / \
        4   8
       /   / \
      11  13  4
     /  \      \
    7    2      1

递归解法

思路

递归结束条件是当前节点为空返回false 或者当前节点是叶节点, 且root到当前节点的和= sum 返回true. 递归条件是左子树或者右子树有符合条件的结果.

复杂度

时间复杂度:O(n),空间栈复杂度是:O(logn)

代码

public boolean hasPathSum(TreeNode root, int sum) {
        if (root == null) {
            return false;
        }
        if (root.left == null && root.right == null && root.val == sum) {
            return true;
        }
        return hasPathSum(root.left, sum - root.val) || hasPathSum(root.right , sum- root.val);
    }

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.

For example: 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] ]

深度优先搜索

复杂度

时间复杂度:O(n),空间复杂度则取决于满足条件的路径和的数量(假设是k条),则空间是O(klogn)

代码

public List<List<Integer>> pathSum(TreeNode root, int sum) {
        List<List<Integer>> res = new ArrayList<List<Integer>>();
        if (root == null) {
            return res;
        }
        List<Integer> tem = new ArrayList<Integer>();
        tem.add(root.val);
        helper(root, sum, res, tem);
        
        return res;
    }
public void helper(TreeNode root, int sum, List<List<Integer>> res, List<Integer> tem) {
        if (root == null) {
            return;
        }
        if (root.left == null && root.right == null && root.val == sum) {
            res.add(new ArrayList<Integer>(tem));
            return;
        }
        if (root.left != null) {
            tem.add(root.left.val);
            helper(root.left, sum - root.val, res, tem);
            tem.remove(tem.size() - 1);
        }
        if (root.right != null) {
            tem.add(root.right.val);
            helper(root.right, sum - root.val, res, tem);
            tem.remove(tem.size() - 1);
        }
    }

lpy1990
26 声望10 粉丝