Given a binary tree and a sum, find all root-to-leaf paths where each path‘s sum equals the given sum.
For example:sum
= 22
,
5 / 4 8 / / 11 13 4 / \ / 7 2 5 1
return
[ [5,4,11,2], [5,8,4,5] ]
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; }
原文:http://blog.csdn.net/mnmlist/article/details/44655107