博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
112. Path Sum - Easy
阅读量:6877 次
发布时间:2019-06-26

本文共 964 字,大约阅读时间需要 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.

Note: A leaf is a node with no children.

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.

 

time: O(n), space: O(height)

/** * Definition for a binary tree node. * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */class Solution {    public boolean hasPathSum(TreeNode root, int sum) {        if(root == null) {            return false;        }        if(root.left == null && root.right == null) {            return sum - root.val == 0;        }        return hasPathSum(root.left, sum - root.val) || hasPathSum(root.right, sum - root.val);    }}

 

转载于:https://www.cnblogs.com/fatttcat/p/10198680.html

你可能感兴趣的文章
ISO 9126质量模型:软件质量模型的6大特性和27个子特性
查看>>
一个 rm -rf的教训
查看>>
几何画板添加背景图片方法
查看>>
用main函数传参做简单的计算器的代码
查看>>
Bash终端命令行,使用privoxy将socks代理转成http代理
查看>>
Linux基础命令
查看>>
if case 语句 find locate 文件查找 和 压缩解压缩工具 简介
查看>>
Linux常用命令——tr
查看>>
检测 ip 是否断开,并使用邮箱报警
查看>>
整理第一周学习C的知识点
查看>>
Spring Data JPA 实例查询
查看>>
ping多线程
查看>>
PMP每日一题
查看>>
python中struct.unpack的用法
查看>>
解决物理内存足够时VMware 提示物理内存不足。。。
查看>>
java socket常见异常
查看>>
Dubbo与Zookeeper、SpringMVC整合和使用
查看>>
Spring中的属性scope
查看>>
SpringApplication你不知道的那些事!
查看>>
为什么比别人办事效率慢?因为你没用这几款强大的搜索软件!
查看>>