Leetcode

Leetcode-Path Sum

2017-10-04  本文已影响0人  Juliiii

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

这道题一看就是深度优先搜索的问题了。题意很简单,就是从找一个条路,从根部到叶子,其中节点的值加起来等于给定的值。那就遍历每个节点,每次到达一个新的叶子节点时,加上当前结点的值,看是否等于给定的值,如果是,那么就找到了。如果不是,退回上一层继续遍历,直到遍历完整个树,如果还找不到,那就无解。

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;
        }
    }
};
上一篇下一篇

猜你喜欢

热点阅读