博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LeetCode 112: Path Sum
阅读量:4149 次
发布时间:2019-05-25

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

Question:

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.

分析:

题目要求在树中找到一条总和等于Sum的路径,等价于在树的左右两个子树中找到和等于sum-root的路径,这样依次递归。

代码如下:

/** * Definition for binary tree * 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==NULL)		return false;	if(root->left ==NULL && root->right==NULL)		return sum == root->val;	if (root->left && hasPathSum(root->left, sum-root->val))		return true;	if (root->right && hasPathSum(root->right, sum-root->val))		return true;	return false;    }};

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

你可能感兴趣的文章
matlab中inline的用法
查看>>
如何用matlab求函数的最值?
查看>>
Git从入门到放弃
查看>>
java8采用stream对集合的常用操作
查看>>
EasySwift/YXJOnePixelLine 极其方便的画出真正的一个像素的线
查看>>
Ubuntu系统上安装Nginx服务器的简单方法
查看>>
Ubuntu Linux系统下apt-get命令详解
查看>>
ubuntu 16.04 下重置 MySQL 5.7 的密码(忘记密码)
查看>>
Ubuntu Navicat for MySQL安装以及破解方案
查看>>
HTTPS那些事 用java实现HTTPS工作原理
查看>>
oracle函数trunc的使用
查看>>
MySQL 存储过程或者函数中传参数实现where id in(1,2,3,...)IN条件拼接
查看>>
java反编译
查看>>
Class.forName( )你搞懂了吗?——转
查看>>
jarFile
查看>>
EJB3.0定时发送jms(发布/定阅)方式
查看>>
EJB与JAVA BEAN_J2EE的异步消息机制
查看>>
数学等于号是=那三个横杠是什么符
查看>>
HTTP协议详解
查看>>
java多线程中的join方法详解
查看>>