美文网首页
112.Path Sum

112.Path Sum

作者: analanxingde | 来源:发表于2018-10-12 09:12 被阅读6次

题目

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.

Note: A leaf is a node with no children.

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.

思路:DFS递归

可以将此问题转化为左右子树是否存在何为sum-root->val的子情况。
这种问题bool函数一般分四步:

  1. 特殊情况为空为零的
  2. 返回值为true的终止情况
  3. 递归调用子函数的返回值判断情况
  4. 其余情况,返回值为false
    四步处理中应保证第二步第四步都有返回。
/**
 * 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)//1.
            return false;
        int sub=sum-root->val;
        if(sub==0 && root->left==nullptr && root->right==nullptr)//2.
            return true;
        if(hasPathSum(root->left,sub)||hasPathSum(root->right,sub))//3.
            return true;
        return false;//4.
    }
};

相关文章

网友评论

      本文标题:112.Path Sum

      本文链接:https://www.haomeiwen.com/subject/lldwaftx.html