您的位置:首页 > 其它

leetcode_113_Path Sum II

2015-03-26 20:24 477 查看

描述:

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;
}

结果:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: