Leetcode-Path Sum

Description

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.

Explain

這道題一看就是深度優(yōu)先搜索的問題了。題意很簡(jiǎn)單,就是從找一個(gè)條路,從根部到葉子,其中節(jié)點(diǎn)的值加起來(lái)等于給定的值。那就遍歷每個(gè)節(jié)點(diǎn),每次到達(dá)一個(gè)新的葉子節(jié)點(diǎn)時(shí),加上當(dāng)前結(jié)點(diǎn)的值,看是否等于給定的值,如果是,那么就找到了。如果不是,退回上一層繼續(xù)遍歷,直到遍歷完整個(gè)樹,如果還找不到,那就無(wú)解。

Solution

/**
 * Definition for a binary tree node.
 * 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) {
        bool flag = false;
        if (!root) return false;
        dfs(flag, root, sum, 0);
        return flag;      
    }
    void dfs(bool& flag, TreeNode* root, int sum, int _sum) {
        if (flag) return;
        if (root) {
            dfs(flag, root->left, sum,_sum + root->val);
            dfs(flag, root->right, sum,_sum + root->val);
            _sum += root->val;
            if(!root->left&&!root->right&&_sum == sum) flag = true;
        }
    }
};
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容