首页 > 其他 > 详细

Solution 4: 二叉树的路径和

时间:2015-06-28 21:32:37      阅读:137      评论:0      收藏:0      [点我收藏+]

问题描述

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

例如,输入整数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);
	}
}

  

 

Solution 4: 二叉树的路径和

原文:http://www.cnblogs.com/harrygogo/p/4606050.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!