let 113. Path Sum II

主题思想: 递归回溯, 关键点在于什么时候选择回溯,什么时候应该结束。

当遇到null 时结束,则应该在遍历完一个节点的左右子树过后,再删除栈顶元素。

AC 代码:

/**
 * 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>> ans=new ArrayList<List<Integer>>();
        if(root==null) return ans;

        findPath(root,new ArrayList<Integer>(), ans,0,sum);

        return ans;
    }

    public  void findPath(TreeNode root, List<Integer> tmpList,List<List<Integer>> ans,int tmp,int sum){

        if(root==null) return ;

        tmpList.add(root.val);
        if(root.left==null&&root.right==null){
            if(tmp+root.val==sum){
                ans.add(new ArrayList<Integer>(tmpList));
            }
        }

        findPath(root.left,tmpList,ans,tmp+root.val,sum);

        findPath(root.right,tmpList,ans,tmp+root.val,sum);
        //here is important
        tmpList.remove(tmpList.size()-1);
    }
}

猜你喜欢

转载自blog.csdn.net/the_conquer_zzy/article/details/79200905