算法Week08.03 - LeetCode 112. Path Sum

来源:互联网 发布:烬技能数据 编辑:程序博客网 时间:2024/06/06 17:08

题意

给出一棵二叉树,判断是否存在一条从根到叶子的路径,使得这条路径上所有节点上的val 的和与给出的sum 相等。

难度

Easy

解题思路

一道经典的深度优先搜索题,复杂度为 O(v+e)。

源代码

 
 class Solution {
 public:
     bool hasPathSum(TreeNode* root, int sum) {
         return dfs(root, 0, sum);
     }
     bool dfs(TreeNode* root, int sum, const int &target) {
         if (root) {
             sum += root->val;
             if (!root->left && !root->right) {
                 if (sum == target) return true;
                 else return false;
             }
             else {
                 return dfs(root->left, sum, target) || dfs(root->right, sum, target);
             }
         }
         return false;
     }
 };
0 0
原创粉丝点击