LeetCode题解——Path Sum
2015-11-17 21:55
246 查看
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
return true, as there exist a root-to-leaf path
it's easy to use recursion to solve the problem
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->2which sum is 22.
it's easy to use recursion to solve the problem
/** * Definition for a binary tree node. * 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) return false; if(!root->left && !root->right) return sum==root->val; bool flage = false; if(root->left) flage = hasPathSum(root->left,sum-root->val); if(flage) return true; else{ if(root->right) return hasPathSum(root->right,sum-root->val); else return false; } } };
相关文章推荐
- HIHO_Disk Storage
- vi 中常用命令技巧
- 简述Android 百分比布局支持库(android-percent-support)
- 蓝桥杯 历届试题 矩阵翻硬币
- 【计算机网络】子网掩码什么用?什么是网段?什么叫做在“同一网段”?
- EditText+ListView实现从动态显示数据库数据
- LeetCode题解——Sum Root to Leaf Numbers
- 给大家介绍点技术博客,希望对大家有帮助~
- poj2010
- Firebird 3.0 新功能
- UISegmentedControl
- LeetCode79——Word Search
- Webkit之常用对象API梳理
- hadoop——倒排索引
- Reverse Words in a String
- 【郝斌数据结构自学笔记】12-13_连续存储数组的算法演示
- JMeter处理Cookie与Session
- 【python游戏编程之旅】第二篇--pygame中的IO、数据
- 五笔字根助记词
- 五笔字根助记词