113. 路径总和 II-LeetCode

心得:使用回溯法,注意节点的添加与删除,

添加一个节点和删除一个节点最好放在同一段递归!!

以前放在不同递归,但感觉很容易错。

/**
 * 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>> list=new LinkedList<>();
            if(root==null)
                return list;
            rec(root,list,new LinkedList(),sum);
            return list;
        }
      public void rec(TreeNode root,List<List<Integer>> list,LinkedList<Integer> tmp,int sum)
      {
          if(root==null)
              return;
        
          if(root.left==null&&root.right==null&&(sum-root.val==0))
             {
              tmp.add(root.val);
              List<Integer> newList=new LinkedList<>();
              for(Integer a:tmp)
              {
                  newList.add(a);
              }
              list.add(newList);    
                tmp.removeLast();
             }
          else{
              tmp.add(root.val);
              rec(root.left,list,tmp,sum-root.val);
              rec(root.right,list,tmp,sum-root.val);
              tmp.removeLast();
          }
      }

}

 

posted @ 2019-05-23 21:21  pc_m  阅读(101)  评论(0编辑  收藏  举报