LeetCode 113. Path Sum II
2018-03-13 17:46
471 查看
描述
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,
return
思路:首先需要一种遍历算法(前序、中序、后序),这里可以选择前序遍历,关键是需要将之前经过的经过的元素保存起来,这里就可以使用栈进行保存,当进入方法时,就将当前的节点保存到栈中,然后遍历左子树与右子树,遍历完之后即将该元素出栈。当遍历到了叶子节点时,即可将栈中的所有元素相加,看是否符合条件,若符合,则保存。代码见下。
代码(c#)
总结
在需要获取二叉树的所有路径时,可以考虑使用前序遍历+栈保存的方式。
相关链接
LeetCode原题:https://leetcode.com/problems/path-sum-ii/description/
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] ]
思路:首先需要一种遍历算法(前序、中序、后序),这里可以选择前序遍历,关键是需要将之前经过的经过的元素保存起来,这里就可以使用栈进行保存,当进入方法时,就将当前的节点保存到栈中,然后遍历左子树与右子树,遍历完之后即将该元素出栈。当遍历到了叶子节点时,即可将栈中的所有元素相加,看是否符合条件,若符合,则保存。代码见下。
代码(c#)
public IList<IList<int>> PathSum(TreeNode root, int sum) { Stack<int> stack = new Stack<int>(); IList<IList<int>> list = new List<IList<int>>(); if(root==null) return list; PathSum(root, sum, stack, list); return list; } public void PathSum(TreeNode root, int sum,Stack<int> stack,IList<IList<int>> result) { stack.Push(root.val);//保存当前元素 if (root.left == null && root.right == null) { //到了叶子节点 if (stack.Sum() == sum) { result.Add(stack.Reverse().ToList());//得到一条路径 } stack.Pop();//返回上一层前将本节点的元素出栈 return; } if (root.left != null) PathSum(root.left, sum, stack, result); if (root.right != null) PathSum(root.right, sum, stack, result); stack.Pop();//返回上一层前将本节点的元素出栈 }
总结
在需要获取二叉树的所有路径时,可以考虑使用前序遍历+栈保存的方式。
相关链接
LeetCode原题:https://leetcode.com/problems/path-sum-ii/description/
相关文章推荐
- 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 -- JavaScript 代码
- leetCode 113. Path Sum II 二叉树问题 | Medium
- LeetCode 113. Path Sum II(java)
- Leetcode 113. Path Sum II
- [leetcode] 113. Path Sum II 解题报告
- [LeetCode]112. Path Sum&113. Path Sum II
- 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
- 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