首页 > 其他 > 详细

leetcode_113_Path Sum II

时间:2015-03-26 20:51:08      阅读:130      评论:0      收藏:0      [点我收藏+]

描述:

Given a binary tree and a sum, find all root-to-leaf paths where each path‘s sum equals the given sum.

For example:
Given the below binary tree and sum = 22,
              5
             /             4   8
           /   /           11  13  4
         /  \    /         7    2  5   1

return

[
   [5,4,11,2],
   [5,8,4,5]
]

思路:

大致思路就是将pathsum 1中的存储节点的栈stack换成具有栈功能的LinkedList,这样每匹配依次将各个节点的值存储到一个list中,遍历完整棵树后返回一个满足条件的结点列表的列表。

代码:

public List<List<Integer>> pathSum(TreeNode root, int sum){
		List<List<Integer>>list=new ArrayList<List<Integer>>();
		int num=0;
		if (root == null)
			return list;
		List<Integer>subList=new ArrayList<Integer>();
		LinkedList<TreeNode>linkedList=new LinkedList<TreeNode>();
		Stack<TreeNode> st1 = new Stack<TreeNode>();
		linkedList.addLast(root);
		num+=root.val;
		TreeNode top = null;
		while (!linkedList.isEmpty()) {
			top=linkedList.getLast();
			while(top.left!=null)//达到页结点
			{
				linkedList.addLast(top.left);
				num+=top.left.val;
				top=top.left;
			}
			while(!linkedList.isEmpty())
			{
				top=linkedList.getLast();
				if(top.right==null)//无右子树时,访问结点
				{
					if(top.left==null&&num==sum)
					{
						for(int i=0;i<linkedList.size();i++)
							subList.add(linkedList.get(i).val);
						list.add(subList);
						subList=new ArrayList<Integer>();
					}
					linkedList.removeLast();
					num-=top.val;
				}else 
				{
					if(st1.empty()||(!st1.empty()&&st1.peek()!=top))//有右子树且第一次出现,将右子树入栈,并将结点在st1中标记一下
					{
						st1.push(top);
						linkedList.addLast(top.right);
						num+=top.right.val;
						break;//右子树入栈了,然后从右子树开始
					}
					else//有右子树,但是第二次出现了,访问该结点
					{
						st1.pop();
						linkedList.removeLast();
						num-=top.val;
					}
				}
				
			}
		}
		return list;
    }

结果:

技术分享

leetcode_113_Path Sum II

原文:http://blog.csdn.net/mnmlist/article/details/44655107

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