博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[LeetCode] Path Sum, Solution
阅读量:7045 次
发布时间:2019-06-28

本文共 1170 字,大约阅读时间需要 3 分钟。

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.
[Thoughts]
二叉树遍历。遍历过程中累加节点值,当到达任意叶节点的时候,进行判断。
[Code]
1:       bool hasPathSum(TreeNode *root, int sum) {  2:            return hasPathSum(root, 0, sum);      3:       }  4:       bool hasPathSum(TreeNode *root, int sum, int target) {  5:            if(root == NULL) return false;  6:            sum += root->val;  7:            if(root->left == NULL && root->right == NULL) //leaf  8:            {  9:                 if(sum == target)  10:                      return true;  11:                 else  12:                      return false;  13:            }  14:            return hasPathSum(root->left, sum, target)   15:                   || hasPathSum(root->right, sum, target);      16:       }

转载于:https://www.cnblogs.com/codingtmd/archive/2013/03/24/5078881.html

你可能感兴趣的文章
《大话操作系统——扎实project实践派》(8.2)(除了指令集.完)
查看>>
SAP 物料移动类型查询表
查看>>
Unity UGUI——Rect Transform包(Anchors)
查看>>
SNMP 实战1
查看>>
ZooKeeper概述(转)
查看>>
[nodejs] nodejs开发个人博客(一)准备工作
查看>>
Android仿微信界面--使用Fragment实现(慕课网笔记)
查看>>
泪奔在最后时刻
查看>>
vsearch 去除重复序列和singleton 序列
查看>>
Android——计算器第一次完善
查看>>
【DDD/CQRS/微服务架构案例】在Ubuntu 14.04.4 LTS中运行WeText项目的服务端
查看>>
第四节,Linux基础命令
查看>>
使用SignalR 提高B2C商城用户体验1
查看>>
javaScript系列:js中获取时间new Date()详细介绍
查看>>
搭建Go开发及调试环境(LiteIDE + GoClipse) -- Windows篇
查看>>
[RxJS] Multicasting shortcuts: publish() and variants
查看>>
删除注释云平台JS,加快DISCUZ访问
查看>>
ThreadPoolExecutor
查看>>
JeeSite环境搭建及运行和打包(master20161117)
查看>>
Flink -- Failover
查看>>