[Leet Code]Path Sum II

此题如果 #1 和 #4 判断分支交换,大集合就会超时(因为每次对于非叶子节点都要判断是不是叶子节点)。可见,有时候if else判断语句也会对于运行时间有较大的影响。

import java.util.ArrayList;



class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode(int x) { val = x; }
}

public class Solution {
    private int currSum = 0;
    private ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
    private ArrayList<Integer> tryPath = new ArrayList<Integer>();
    private ArrayList<Integer> oneSuccPath;
    
    public ArrayList<ArrayList<Integer>> pathSum(TreeNode root, int sum) {
        result.clear();
        tryPath.clear();
        
        if (null == root)
            return result;
        
        pathSumCore(root, sum);
        return result;
    }
    
    public void pathSumCore(TreeNode root, int sum) {
        // Start typing your Java solution below
        // DO NOT write main() function
        if (null == root)
            return;
        
        currSum += root.val;
        tryPath.add(root.val);

        // #1 左右孩子都有
        if (null != root.left && null != root.right) {    
            pathSumCore(root.left, sum);
            pathSumCore(root.right, sum);
            currSum -= root.val;
            tryPath.remove(tryPath.size()-1);
            return;
        }
        // #2 只有右孩子
        else if (null == root.left && null != root.right) {
            pathSumCore(root.right, sum);
            currSum -= root.val;
            tryPath.remove(tryPath.size()-1);
            return;
        }
        // #3 只有左孩子
        else if (null == root.right && null != root.left) {
            pathSumCore(root.left, sum);
            currSum -= root.val;
            tryPath.remove(tryPath.size()-1);
            return;
        }
        // #4 叶子节点
        else {//只有叶子节点才判断,其他情况都要继续往深去判断
            if (currSum == sum) {
                oneSuccPath = new ArrayList<Integer>(tryPath);
                result.add(oneSuccPath);
                currSum -= root.val;
                tryPath.remove(tryPath.size()-1);
                return;
            }
            else {
                currSum -= root.val;
                tryPath.remove(tryPath.size()-1);
                return;
            }
        }
    }
    
    public static void main(String[] args) {
        TreeNode a = new TreeNode(1);
        TreeNode b = new TreeNode(-2);
        TreeNode c = new TreeNode(-3);
        TreeNode d = new TreeNode(1);
        TreeNode e = new TreeNode(3);
        TreeNode f = new TreeNode(-2);
        TreeNode g = new TreeNode(-1);

        a.left = b;
        a.right = c;
        b.left = d;
        b.right = e;
        c.left = f;
        d.left = g;

        Solution sl = new Solution();
        sl.pathSum(a, 2);
    }
}
原文地址:https://www.cnblogs.com/lihaozy/p/3208513.html