算法作业HW11:Leetcode90 Path Sum

来源:互联网 发布:centos如何输入命令 编辑:程序博客网 时间:2024/06/07 02:31

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.

Note:

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.

Solution:

  Analysis and Thinking:

本体要求依据数的二叉树以及给定的和值sum,判断二叉树中是否存在路径,使得路径上所有节点相加的值等于sum值,有则返回True,否则返回False。这一题最简单的解法之一就是利用递归法的思想,结合深度遍历树的做法。重点在于:一是特殊情况处理如输入的是空树则对于任sum值都为false。二是对于递归的当前节点为空,说明路径不同,返回false。三是若当前节点为叶节点,且值等于输入的sum值,返回true。最后是如果非叶节点,深度遍历左右子树。

 

  Steps:

1.判断当前节点是否为空,如果是,返回false

2.判断当前节点是否为叶节点,如果是,且其值等于参数sum值,返回true

3.将sum减去当前节点值,模拟出一个按路径相加的效果,深度遍历当前节点的左右子树



Codes:

class Solution{public:    bool hasPathSum(TreeNode *root,int sum)    {        if(root==NULL) return false;  //判断当前节点是否为空,若是,返回false,不通                if(!root->left&&!root->right&&root->pointValue==sum) return true;  //当前为叶节点,且节点值等于参数sum,说明该路径满足条件                int record=sum-root->pointValue;  //减去当前节点值,相当于记录了路径的相加和的效果        return hasPathSum(root->left,record)||hasPathSum(root->right,recorc); //搜索当前节点左右子树    }};



Results:


原创粉丝点击