路径总和-力扣112

76 阅读1分钟

路径总和-力扣112

先根遍历整棵树,访问当前结点时判断当前结点是否是叶子结点,如果是,则判断其路径上的值是否等于targetNum,如果不是则继续向下传递路径值。

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:

    bool ans = false;

    void getNum(TreeNode* root, int num, int targetSum){
        if(root == nullptr) return; // 递归出口

        if(root->left == nullptr && root->right == nullptr){ // 如果是叶子结点
            if(root->val + num == targetSum) ans = true; // 存在符合标准的路径
        }
        getNum(root->left, num + root->val, targetSum);
        getNum(root->right, num + root->val, targetSum);
    }

    bool hasPathSum(TreeNode* root, int targetSum) {
        if(root == nullptr) return false;
        if(root->left == nullptr && root->right == nullptr){ // 如果是叶子结点
            if(root->val  == targetSum) return true; // 存在符合标准的路径
        }
        getNum(root->left, root->val, targetSum);
        getNum(root->right, root->val, targetSum);
        return ans;
    }
};

时间复杂度:O(n)O(n)

空间复杂度:平均O(logn)O(logn),最坏O(n)O(n)