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; }
结果:
相关文章推荐
- LeetCode:113 Path Sum II
- [Leetcode 113, Medium] Path sum II
- LeetCode 113:Path Sum II
- [LeetCode 113] Path Sum II
- leetcode 113 —— Path Sum II
- LeetCode113 Path Sum II
- LeetCode 113: Path Sum II 二叉树遍历
- [Leetcode 34] 113 Path Sum II
- leetcode——113——Path Sum II
- LeetCode113 Path Sum II
- 【LeetCode】112,113,437. Path Sum I, II, III
- leetcode-113-Path Sum II
- LeetCode(113) Path Sum II
- Leetcode 笔记 113 - Path Sum II
- LeetCode(113) Path Sum II
- leetcode 113 Path Sum II
- LeetCode113—Path Sum II
- LeetCode 113 Path Sum II
- [LeetCode]题解(python):113-Path Sum II
- 【LeetCode-面试算法经典-Java实现】【113-Path Sum II(路径和)】