LeetCode: Path Sum [112]
来源:互联网 发布:大数据技术研究方向 编辑:程序博客网 时间:2024/05/17 02:17
【题目】
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.
【题意】
判断二叉树中是否存在一条从根到叶子节点的路径,使得路径上的节点值之和等于所给的值【思路】
【代码】
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public: bool dfs(TreeNode*root, int pathSum, int sum){ pathSum+=root->val; if(root->left==NULL && root->right==NULL){ return pathSum==sum; } //搜索左子树 bool hasLeft=false; if(root->left) hasLeft=dfs(root->left, pathSum, sum); //搜索右子树 bool hasRight=false; if(root->right) hasRight=dfs(root->right, pathSum, sum); return hasLeft || hasRight; } bool hasPathSum(TreeNode *root, int sum) { if(root==NULL)return false; int pathSum=0; return dfs(root, pathSum, sum); }};
0 0
- LeetCode(112)Path Sum
- LeetCode 112 Path Sum
- LeetCode: Path Sum [112]
- 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
- 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
- LeetCode 112:Path Sum
- Struts2动态方法调用
- MySQL权限分配
- oracle学习之bulk collect用法
- 两分钟学会Unity3D布娃娃的使用
- Contiki:一个鲜为人知的、主宰物联网的开源操作系统
- LeetCode: Path Sum [112]
- C/C++堆、栈及静态数据区详解
- 16_leetcode_swap node in pairs
- java-IO操作性能对比
- 存储过程的优缺点及使用场景
- Java内存管理简析
- 如何在Ubuntu14.04上运行32位程序
- Java 守护线程
- 开发者揭秘Swift语言有哪些优点?