LeetCode (12) Path Sum (二叉树路径和判断)
来源:互联网 发布:java代码漏洞扫描工具 编辑:程序博客网 时间:2024/05/20 17:23
题目描述
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.
因此,本题要求判断二叉树某一条路径的和是否为给定的数值。本题的思路为深度优先搜索。
/** * 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 hasPathSum(TreeNode *root, int sum) { if (root == NULL) { return false; } if (!root->left && !root->right && root->val == sum) return true; if (hasPathSum(root->left, sum-root->val)) return true; else if (hasPathSum(root->right, sum-root->val)) return true; else return false; }};
0 0
- LeetCode (12) Path Sum (二叉树路径和判断)
- Path Sum 二叉树路径和 @LeetCode
- [LeetCode]112. Path Sum(判断二叉树根到叶路径和是否等于sum)
- 【leetcode 二叉树路径和】Path Sum 和 Path Sum II
- leetcode系列(24)Path Sum 判断二叉树中和为Sum的路径是否存在
- [LeetCode]437. Path Sum III(求二叉树中路径和等于sum的数量)
- Path Sum II 二叉树路径和,打印所有路径 @LeetCode
- LeetCode Path Sum 路径和
- [LeetCode] 路径和 Path Sum
- leetcode Path Sum 路径和
- Binary Tree Maximum Path Sum (二叉树路径和的最大值) 【leetcode】
- Binary Tree Maximum Path Sum 二叉树最大路径和 @LeetCode
- LeetCode(Binary Tree Maximum Path Sum) 在二叉树中找出一条和最大的路径
- Leetcode 124 Binary Tree Maximum Path Sum 二叉树最大路径和
- LeetCode 124. Binary Tree Maximum Path Sum(二叉树最大路径和)
- LeetCode 437. Path Sum III 题解 和固定的二叉树路径数目
- leetcode解题之112 & 113 & 437. Path Sum java版(二叉树路径和)
- 【LeetCode】Binary Tree Maximum Path Sum二叉树中的最大路径和
- 期望、方差、协方差和矩
- 【C#】 24. HybridLocalSearchSolver + 自定义函数调用 + AddConstraint (constraint===1)
- HDU 5029(三维正方形)
- DirectX9 投影
- poj1004
- LeetCode (12) Path Sum (二叉树路径和判断)
- 剑指offer面试28
- 遥感图像快速传输算法
- 算法题8
- VC颜色区分故障
- 07-图5. 旅游规划(25)
- 计算机体系结构Computer Architecture
- TextView 设置成一条分割线
- 垃圾回收