找出二叉树中所有和为给定值的路径

//找出二叉树中所有和为给定值的路径,以数组的形式打印出来
//采用深搜的方法来实现
public List> pathSum(TreeNode root, int sum){
	List> result = new LinkedList>();
	List currentResult = new LinkedList();
	pathSum(root,sum,currentResult, result);
	return result;
}
public void pathSum(TreeNode root, int sum, ListcurrentResult, List> result){
	if(root == null){
		return;
	}
	currentResult.add(new Integer(root.val));
	//当前结点是叶子结点并且当前路径满足情况
	if(root.left == null && root.right == null &&  sum ==  root.val){
		result.add(new LinkedList(currentResult));
		//再进行回溯
		currentResult.remove(currentResult.size() - 1);
		//已经找到了一条路径,退出当前的递归过程
		return;
	}
	//分别递归到左右子树中去
	else{
		pathSum(root.left, sum - root.val, currentResult, result);
		pathSum(root.right, sum - root.val, currentResult, result)
	}
	//再回溯,从而转入下一条路径
	currentResult.remove(currentResult.size() - 1);
}

你可能感兴趣的:(每日编程)