【leetcode】112. Path Sum
来源:互联网 发布:php array sort 排序 编辑:程序博客网 时间:2024/05/29 12:44
题目描述:
Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.
For example:
Given the below binary tree and sum = 22,
return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22.
思路:
用深度优先搜索遍历整个二叉树。这里我用迭代实现DFS,一般用堆栈实现。此外,为了找到节点和为sum的路径,想到用另一个堆栈来记录遍历到的节点到根节点的和。
代码如下:
public class Solution { public boolean hasPathSum(TreeNode root, int sum) { if(root == null) return false; Stack<TreeNode> node = new Stack();//记录遍历到的节点 Stack<Integer> valSum = new Stack();//记录节点到根节点的和 node.push(root); valSum.push(root.val); while( !node.isEmpty() ){ TreeNode tempRoot = node.pop(); int getSum = valSum.pop(); if(getSum == sum && tempRoot.left == null && tempRoot.right == null){ return true; } if(tempRoot.left != null){ node.push(tempRoot.left); valSum.push(tempRoot.left.val+getSum); } if(tempRoot.right != null){ node.push(tempRoot.right); valSum.push(tempRoot.right.val+getSum); } } return false; }}
测试通过。
写完了DFS,再试着用BFS实现层次遍历二叉树。思路差不多:
public class Solution { public boolean hasPathSum(TreeNode root, int sum) { if (root == null) return false; Queue<TreeNode> queue = new LinkedList<TreeNode>(); Queue<Integer> value = new LinkedList<Integer>(); queue.offer(root); value.offer(root.val); while(!queue.isEmpty()){ TreeNode tempRoot = queue.poll(); int getSum= value.poll(); if (tempRoot.left == null && tempRoot.right == null && getSum == sum){ return true; } if (tempRoot.left != null) { queue.offer(tempRoot.left); value.offer(getSum + tempRoot.left.val); } if (tempRoot.right != null) { queue.offer(tempRoot.right); value.offer(getSum + tempRoot.right.val); } } return false; }}
看了一下top答案,都是用递归实现DFS的,代码更简洁。如下:
public class Solution { public boolean hasPathSum(TreeNode root, int sum) { if(root == null) return false; if(root.left == null && root.right == null && sum == root.val) return true; return hasPathSum(root.left, sum - root.val) || hasPathSum(root.right, sum - root.val); }
1 0
- LeetCode 112. Path Sum
- [LeetCode]112.Path Sum
- 【LeetCode】112.Path Sum
- [Leetcode] 112. Path Sum
- [leetcode] 112.Path Sum
- 112. Path Sum LeetCode
- Leetcode 112. Path Sum
- LeetCode *** 112. Path Sum
- leetcode-112. Path Sum
- Leetcode 112. Path Sum
- 112.[Leetcode]Path Sum
- LeetCode 112. Path Sum
- Leetcode 112. Path Sum
- 【leetcode】112. Path Sum
- Leetcode 112. Path Sum
- LeetCode - 112. Path Sum
- [Leetcode]112. Path Sum
- LeetCode 112. Path Sum
- JVM学习笔记(四):Class文件结构
- 功能强大的Vitamio视频播放器的使用教程
- [00014]排序不支持原生比较的对象
- [BZOJ]1055: [HAOI2008]玩具取名 DP
- Android-贝塞尔曲线
- 【leetcode】112. Path Sum
- ELF文件-段和程序头
- derby spring mybatis 集成
- Android ViewFlipper 简单应用
- 奔驰车身类型编码
- Android 贝塞尔曲线的魅力
- 第二十课 字符串库
- 字符串分段并添加集合中
- vim编辑器相关命令