博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Path Sum--路径和(重)
阅读量:4108 次
发布时间:2019-05-25

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

问题:

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.

解答:

DFS或者BFS。同时,当本节点是叶子节点才判断和,否则节点为空时返回false

参考:

代码:

class Solution {public:    bool hasPathSum(TreeNode *root, int sum) {		return DFS(root, 0, sum);    }	bool DFS(TreeNode *root, int sum, int target)	{		if(root == NULL)			return false;		if(root->left == NULL && root->right == NULL)			return (target == sum + root->val);		return DFS(root->left, sum+root->val, target) || DFS(root->right, sum+root->val, target);	}};

转载地址:http://ektsi.baihongyu.com/

你可能感兴趣的文章
j2ee-验证码
查看>>
日志框架logj的使用
查看>>
js-高德地图规划路线
查看>>
常用js收集
查看>>
mydata97的日期控件
查看>>
如何防止sql注入
查看>>
maven多工程构建与打包
查看>>
springmvc传值
查看>>
Java 集合学习一 HashSet
查看>>
在Eclipse中查看Android源码
查看>>
Android-Socket登录实例
查看>>
Android使用webservice客户端实例
查看>>
层在页面中的定位
查看>>
[转]C语言printf
查看>>
C 语言 学习---获取文本框内容及字符串拼接
查看>>
C 语言学习 --设置文本框内容及进制转换
查看>>
C 语言 学习---判断文本框取得的数是否是整数
查看>>
C 语言 学习---ComboBox相关、简单计算器
查看>>
C 语言 学习---ComboBox相关、简易“假”管理系统
查看>>
C 语言 学习---回调、时间定时更新程序
查看>>