LeetCode 112. Path Sum路徑總和 (C++)

題目:

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.node

Note: A leaf is a node with no children.spa

Example:code

Given the below binary tree and sum = 22,blog

      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.it

分析:

給定一個二叉樹和一個目標和,判斷該樹中是否存在根節點到葉子節點的路徑,這條路徑上全部節點值相加等於目標和。io

從根節點判斷是否存在一條到葉子節點的路徑和等於目標和,等同於判斷根節點的左右節點到葉子節點的路徑和等於目標和減去根節點的值。class

從給的例子中來看,判斷根節點5是否有路徑和等於22,至關於判斷根節點的左節點4是否有路徑和等於22減去5,也就是17,繼續計算下去,11的時候判斷是否有路徑和等於13,其左葉子節點等於7,不等於13-11,而右葉子節點爲2,等於13-11,返回true。二叉樹

程序:

/**
 * 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) {
        if(root == nullptr) return false;
        if(root->left == nullptr && root->right == nullptr && root->val == sum)
            return true;
        return hasPathSum(root->left, sum-root->val)||hasPathSum(root->right, sum-root->val);
    }
};
相關文章
相關標籤/搜索