算法作业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:
阅读全文
0 0
- 算法作业HW11:Leetcode90 Path Sum
- 算法课第十周作业 | Minimum Path Sum
- Path Sum算法详解
- 算法训练:Path Sum II
- 算法训练:Minimum Path Sum
- Path Sum && Path Sum ||
- 算法Week08.03 - LeetCode 112. Path Sum
- 算法训练:Binary Tree Maximum Path Sum
- 算法系列——Path Sum
- 算法系列——Path Sum II
- 算法系列——Path Sum III
- 15算法课程 112. Path Sum
- 算法课第一周作业 | tow sum
- 算法作业HW21:LeetCode 18 4Sum
- Path Sum
- Path Sum
- Path Sum
- Path Sum
- Android开发前奏(一)
- Windows下PATH,CLASSPATH等环境变量详解
- 华数网络 可以实现 全民 免费上网 服务。
- 算法作业HW12:Leetcode94 Sum Root to Leaf Numbers
- 【简书如何创建专题?】
- 算法作业HW11:Leetcode90 Path Sum
- hadoop学习资源与路线图
- virtualenv创建虚拟环境出错
- TCP/IP协议 三次握手与四次挥手
- easyUI设置datebox、textbox、combox、numberbox的值
- 3.nginx 的基本配置与优化
- 用QGIS将shp转json
- Linux 命令-网络操作命令
- 清空KindEditor编辑器内容