[leetcode] #112 Path Sum (easy)

it2025-11-19  11

原题链接

题意:

给定一个值,求出从树顶到某个叶(没有子节点)有没有一条路径等于该值。

思路:

DFS

Runtime: 4 ms, faster than 100.00% of C++

class Solution { public: bool hasPathSum(TreeNode *root, int sum) { if (root == NULL) return false; if (root->val == sum && root->left==NULL && root->right==NULL) return true; return (root->left != NULL && hasPathSum(root->left, sum - root->val)) || (root->right != NULL && hasPathSum(root->right, sum - root->val)); } };

 

转载于:https://www.cnblogs.com/ruoh3kou/p/9929360.html

最新回复(0)