【leetcode】113.(Medium)Path Sum II

解题思路:
递归


提交代码:

class Solution {
    public List<List<Integer>> pathSum(TreeNode root, int sum) {
        List<List<Integer>>	res=new ArrayList<List<Integer>>();
        if(root==null)	return res;
        List<Integer> curPath=new ArrayList<Integer>();
        curPath.add(root.val);
        
        if(root.left==null&&root.right==null&&root.val==sum) {
        	res.add(curPath);
        	return res;
        }
        if(root.left!=null) {
        curPath.add(root.left.val);
        findPath(root.left,curPath,sum-root.val,res);
        curPath.remove((Integer)root.left.val);
        }
        if(root.right!=null) {
        curPath.add(root.right.val);
        findPath(root.right,curPath,sum-root.val,res);
        }
        return res;
    }
    
    private void findPath(TreeNode root,List<Integer> curPath,
    		int sum,List<List<Integer>> res) {
    	if(root==null)	return;
    	if(root.left==null&&root.right==null&&root.val==sum) {
    		res.add(new ArrayList<>(curPath));
    		return;
    	}

    	if(root.left!=null) {
    	curPath.add(root.left.val);
        findPath(root.left,curPath,sum-root.val,res);
       curPath.remove(curPath.size()-1);
    	}
    	if(root.right!=null) {
        curPath.add(root.right.val);
        findPath(root.right,curPath,sum-root.val,res);
        curPath.remove(curPath.size()-1);
    	}
    }
    
    private void removeValue(int val,List<Integer> path) {
    	for(int i=path.size()-1;i>=0;i--) {
    		if(path.get(i)==val) {
    			path.remove(i);
    			break;
    		}
    	}
    }
    
   
}

运行结果:
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/AXIMI/article/details/85385131