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

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

Path Sum

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.

SOLUTION 1:

相当简单的题目,用递归解决。base case: 如果root是叶子,并且sum为root的值,返回true.

否则在左右分别 找一下就好(调用递归),任何一边返回true都可以的。

1 public boolean hasPathSum(TreeNode root, int sum) { 2         if (root == null) { 3             return false; 4         } 5  6         if (root.left == null && root.right == null && sum == root.val) { 7             return true; 8         } 9 10         return hasPathSum(root.left, sum - root.val)11                 || hasPathSum(root.right, sum - root.val);12     }
View Code

 

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

你可能感兴趣的文章
在windows上秒开应用程序
查看>>
HTML快速入门4
查看>>
JQUERY中字符串和JSON的转换
查看>>
三句话告诉你 mapreduce 中MAP进程的数量怎么控制?
查看>>
wxWidgets第十六课 wxTimer没有调用stop导致崩溃的问题分析
查看>>
centos7.x rsync+inotify实时监控备份
查看>>
LNMP环境下的Nagios搭建
查看>>
5.理想中的Redis5.1 第二代Codis
查看>>
网络通信第四课 C++发送Post请求的完整案例
查看>>
Grafana基础配置文件
查看>>
Linux文件系统之RAID
查看>>
营销人员为何要读《笑傲江湖》?
查看>>
敏捷开发“松结对编程”系列之十:L型代码结构(技术篇之一)
查看>>
C++与MySQL的冲突
查看>>
C# 文件操作类1
查看>>
[unity3d]鼠标拖动and旋转缩放
查看>>
VS2008 使用小技巧 提高编程效率
查看>>
安装Operations Manager代理程序
查看>>
详解Spring MVC 4之ViewResolver视图解析器
查看>>
解析和生成Excel报表方法汇总::.NET发现之旅(七)
查看>>