leetcode 112. Path Sum DFS深度优先遍历
来源:互联网 发布:如何在淘宝网上购物 编辑:程序博客网 时间:2024/05/29 04:35
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,
5
/ \
4 8
/ / \
11 13 4
/ \ \
7 2 1
return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22.
这道题考察的就是每一条路径的sum,找到target即可。
代码如下:
import java.util.ArrayList;import java.util.List;/*class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int x) { val = x; }}*/public class Solution { List<Integer> res=new ArrayList<Integer>(); public boolean hasPathSum(TreeNode root, int sum) { if(root==null) return false; else return bydfs(root,sum); } public boolean bydfs(TreeNode root, int sum) { if(root!=null) { if(root.left==null && root.right==null) return root.val==sum; boolean left = bydfs(root.left, sum-root.val); boolean right = bydfs(root.right, sum-root.val); return left || right; }else return false; }}
下面是C++的做法,就是做一个DFS深度优先遍历
代码如下:
#include <iostream>#include <vector>using namespace std;/*struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {}};*/class Solution {public: bool hasPathSum(TreeNode* root, int sum) { return bydfs(root, 0, sum); } bool bydfs(TreeNode* root, int a, int sum) { if (root == NULL) return false; else { if (root->left == NULL && root->right == NULL) { if (a + root->val == sum) return true; else return false; } else { bool left = bydfs(root->left, a + root->val, sum); bool right = bydfs(root->right, a + root->val, sum); return left || right; } } }};
阅读全文
0 0
- leetcode 112. Path Sum DFS深度优先遍历
- leetcode 113. Path Sum II DFS深度优先遍历
- leetcode 437. Path Sum III 深度优先遍历DFS
- leetcode 687. Longest Univalue Path 深度优先遍历DFS
- <LeetCode><Easy> 112 Path Sum --二叉树深度优先遍历
- leetcode 404. Sum of Left Leaves DFS深度优先遍历
- leetcode 124. Binary Tree Maximum Path Sum 最大路径和 + DFS深度优先搜索
- LeetCode 之 DFS 深度优先遍历
- leetcode 112.Path Sum-树路径和|深度遍历
- leetcode 377. Combination Sum IV 组合之和 + DP动态规划 + DFS深度优先遍历
- leetcode 416. Partition Equal Subset Sum 动态规划DP + DFS深度优先遍历
- leetcode 508. Most Frequent Subtree Sum 一个简单的DFS深度优先遍历的做法
- leetcode 494. Target Sum 深度优先遍历DFS + DP动态规划
- 深度优先遍历DFS
- DFS-深度优先遍历
- DFS深度优先遍历
- 深度优先遍历(DFS)
- DFS 深度优先遍历
- lua loadstring
- 在MySQL中,VARCHAR与CHAR的区别是什么?VARCHAR(50)中的50代表的含义是什么?
- 外卖小程序发布商品时,要注意的地方-微信小程序教程32
- linux基本命令总结
- Android Interpolator动画属性——设置动画速度
- leetcode 112. Path Sum DFS深度优先遍历
- Ajax原理及其方法详解
- CentOS中安装jdk1.8详细步骤
- c++ vector初始化
- 找工作专门杂记!
- SourceTree的使用
- 记腾讯机器学习基础研究岗2017年秋招笔试
- java面试题
- Byte Short Int Long的长度