Path Sum
来源:互联网 发布:topsurv怎么连接网络 编辑:程序博客网 时间:2024/05/11 22:27
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.
Have you met this question in a real interview?
思路:还是树的递归问题,把握好递归的结束条件,这种题还是很有规律的
代码如下:
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */public class Solution { private boolean flag = false; public boolean hasPathSum(TreeNode root, int sum) { dfs(root,sum,0); return flag; } public void dfs(TreeNode root,int sum,int cur){ if(root==null) { return; }else{ cur = cur+root.val; //保证已经到达叶子节点,是一条完整的路径 if(cur==sum && root.right==null &root.left==null){ flag = true; } } dfs(root.left,sum,cur); dfs(root.right,sum,cur); }}
0 0
- Path Sum && Path Sum ||
- Path Sum
- Path Sum
- Path Sum
- Path Sum
- Path Sum
- Path Sum
- Path Sum
- Path Sum
- Path Sum
- Path Sum
- Path Sum
- Path Sum
- Path Sum
- Path Sum
- Path Sum
- Path Sum
- Path Sum
- 黑马程序员-----JAVA新特性
- Eclipse - 快捷键的设置
- 修改keystore密码别名等
- linux 多线程一篇挺好的文章(包括参数处理)
- leetcode 35: Search Insert Position
- Path Sum
- MySQL主从复制(Master-Slave)与读写分离(MySQL-Proxy)实践
- checkbox数据回显问题
- 《C语言及程序设计》实践项目——初练结构体
- [moses笔记]编译含有nplm的moses解码器
- 多线程服务器的常用编程模型
- LeetCode--Search in Rotated Sorted Array
- int、char、string型字符相互转换
- Spark读取文件