Solution 4: 二叉树的路径和

问题描述

输入一个整数和一颗二叉树,从树的根节点开始往下访问一直到叶节点所经过的所有节点形成一条路径,打印出和与输入整数相等的所有路径。

例如,输入整数19和如下的二叉树

则打印出两条路径:10,5,4和10,9.

解决思路

假设二叉树中的节点的值均大于0,递归思想。

程序

public class TreePathSum {
	public List<List<Integer>> getTreePathSum(TreeNode root, int sum) {
		List<List<Integer>> res = new ArrayList<List<Integer>>();
		if (root == null) {
			return res;
		}
		List<Integer> path = new ArrayList<Integer>();
		helper(root, sum, path, res);

		return res;
	}

	private void helper(TreeNode root, int sum, List<Integer> path,
			List<List<Integer>> res) {
		if (root == null) {
			return;
		}
		if (sum == root.val) {
			path.add(root.val);
			res.add(new ArrayList<Integer>(path));
			path.remove(path.size()-1);
			return;
		}
		
		path.add(root.val);
		helper(root.left, sum - root.val, path, res);
		helper(root.right, sum - root.val, path, res);
		path.remove(path.size() - 1);
	}
}

  

原文地址:https://www.cnblogs.com/harrygogo/p/4606050.html