Binary Tree - Path Sum總結

Path Sum I

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.

Note: A leaf is a node with no children.

Example:

Given the below binary tree and sum = 22,

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

思路:就是判斷leaf的sum是否等於target,用傳參 + node.val 的辦法來進行backtracking,不用寫,自動就做了。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public boolean hasPathSum(TreeNode root, int sum) {
        return hasHelper(root, sum, 0);
    }
    
    private boolean hasHelper(TreeNode node, int target, int cursum) {
        if(node == null) {
            return false;
        }
        if(node.left == null && node.right == null) {
            cursum += node.val;
            return cursum == target;
        }
        return hasHelper(node.left, target, cursum + node.val) ||
            hasHelper(node.right, target, cursum + node.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.

Note: A leaf is a node with no children.

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

思路:就是backtracking,加完了,判斷完了,要remove;remove list 最後一個是 remove(list.size() -1);

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public List<List<Integer>> pathSum(TreeNode root, int sum) {
        List<List<Integer>> lists = new ArrayList<List<Integer>>();
        if(root == null) {
            return lists;
        }
        List<Integer> list = new ArrayList<Integer>();
        dfs(root, sum, 0, lists, list);
        return lists;
    }
    
    private void dfs(TreeNode node, int target, int cursum, List<List<Integer>> lists, 
                    List<Integer> list) {
        if(node == null) {
            return;
        }
        if(node.left == null && node.right == null ) {
            cursum += node.val;
            list.add(node.val);
            if(cursum == target) {
                lists.add(new ArrayList<Integer>(list));
            }
            list.remove(list.size() -1);
            return;
        }
        list.add(node.val);
        dfs(node.left, target, cursum + node.val, lists, list);
        list.remove(list.size() - 1);
        
        list.add(node.val);
        dfs(node.right, target, cursum + node.val, lists, list);
        list.remove(list.size() - 1);
    }
}

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

      10
     /  \
    5   -3
   / \    \
  3   2   11
 / \   \
3  -2   1

Return 3. The paths that sum to 8 are:

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

思路:就是以每一個node,爲start point,進行計算,如果path - node.val = sum,那麼就return 1;

pathSumHelper 就是記錄包含當前node的所有計算count。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public int pathSum(TreeNode root, int sum) {
        if(root == null) {
            return 0;
        }
        // pathSumHelper 從node開始算;包含node;
        int cursum = pathSumHelper(root, sum);
        // pathSum 可以不從root開始,也就是root
        int leftsum = pathSum(root.left, sum);
        int rightsum = pathSum(root.right, sum);
        return cursum + leftsum + rightsum;
    }
    
    // pathSumHelper 從node開始算;包含node;
    private int pathSumHelper(TreeNode node, int sum) {
        if(node == null) {
            return 0;
        } else {
            int cursum = (node.val == sum ? 1 : 0 );
            int leftsum = pathSumHelper(node.left, sum - node.val);
            int rightsum = pathSumHelper(node.right, sum - node.val);
            return cursum + leftsum + rightsum;
        }
    }
}

Given a binary tree, find the maximum path sum.

The path may start and end at any node in the tree.

For example:
Given the below binary tree,

       1
      / \
     2   3

Return 6.

思路: 遞歸返回的包括當前node的最大值,爲什麼只能返回跟root有關的直線sum,因爲返回上去要跟上面的有聯繫才能繼續遞歸,否則如果返回root.val + leftmax + rightmax,那麼返回上去,上面的不知道怎麼用了,因爲不是一條線了;所以只能返回 root.val, root.val + leftmax, root.val + rightmax中的最大值,那麼遞歸的定義就是跟root.val有關的最大值;

root.val + leftmax + rightmax 只是global計算的時候需要;

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public int maxPathSum(TreeNode root) {
        if(root == null) {
            return 0;
        }
        int[] res = {Integer.MIN_VALUE};
        pathSumHelper(root, res);
        return res[0];
    }
    
    private int pathSumHelper(TreeNode root, int[] res) {
        if(root == null) {
            return 0;
        }
        int leftmax = pathSumHelper(root.left, res);
        int rightmax = pathSumHelper(root.right, res);
        int localmax = Math.max(root.val, Math.max(leftmax + root.val, rightmax + root.val));
        res[0] = Math.max(res[0], Math.max(localmax, leftmax + rightmax + root.val));
        return localmax;
    }
}
發佈了619 篇原創文章 · 獲贊 13 · 訪問量 17萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章