112-Path Sum

類別:DFS
難度:easy

題目描述

這裏寫圖片描述

算法分析

用遞歸的方式,分別對左子樹和右子樹存在的路徑進行和進行判斷。噹噹前節點的左右節點分別爲NULL時,即路徑已經到達葉子節點。

代碼實現

bool hasPathSum(TreeNode* root, int sum) {
    if (root == NULL) return false;
    bool result = false;
    if (root != NULL) {
        findPath(result, root, root->val, sum);
    }
    return result;
}
void findPath(bool& result, TreeNode* root, int total, int& sum) {
    if (root->left == NULL && root->right == NULL) {
        if (total == sum) result = true;
    }
    if (root->left != NULL) {
        findPath(result, root->left, total + root->left->val, sum);
    }
    if (root->right != NULL) {
        vec.push_back(root->right->val);
        findPath(result, root->right, total + root->right->val, sum);
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章