leetcode_113_Path Sum II
来源:互联网 发布:淘宝固定背景尺寸 编辑:程序博客网 时间:2024/05/20 11:25
描述:
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; }
结果:
0 0
- leetcode_113_Path Sum II
- leetcode_113_Path Sum II
- 【Leetcode】Path Sum II (Sum)
- Combination Sum && Combination Sum II
- Combination Sum Combination Sum II
- Combination Sum II
- LeetCode: Combination Sum II
- LeetCode: Combination Sum II
- LeetCode: Path Sum II
- [LeetCode]Combination Sum II
- LeetCode Combination Sum II
- LeetCode Path Sum II
- [Leetcode] Combination Sum II
- [Leetcode] Path Sum II
- LeetCode: Path Sum II
- Path Sum II
- Combination Sum II
- [LeetCode] Path Sum II
- [python]【练手向】24点问题的一个Python解
- Longest Palindromic Substring
- nyoj 58 最少步数 【BFS+优先队列】
- tar命令简介
- 2072.单词数
- leetcode_113_Path Sum II
- 创建mesh
- 禁止浏览器复制和禁止查看源代码
- bzoj 2243 [SDOI2011]染色 树剖+线段树
- 3.数据抽样以及R实现
- C语言
- UISearchBar自定义取消按钮
- VMware_install_cleaner,彻底卸载虚拟机
- p51 第二章 第四题 潘璠