LeetCode解题报告 112. Path Sum [easy]
2017-01-03 11:13
531 查看
题目要求
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->2which sum is 22.
解题思路
题目要求判断是否存在一条从跟节点到叶子节点的路径,路径上的节点之和等于给出的sum。用最基本的DFS即可,判断该节点左右子树是否为空且节点值等于sum,如果是则返回true,而后将sum的值减去跟节点的val值,递归循环判断左孩子节点和右孩子节点,其中一个满足即可。复杂度分析
时间复杂度为O(N)代码如下:
class Solution { public: bool hasPathSum(TreeNode* root, int sum) { if (root==NULL) { return false; } if (root->val==sum&&root->left==NULL&&root->right==NULL) { return true; } sum=sum-root->val; return hasPathSum(root->left, sum)||hasPathSum(root->right, sum); } };
相关文章推荐
- 【LeetCode】26.Remove Duplicates from Sorted Array(Easy)解题报告
- 【LeetCode】53.Maximum Subarray(Easy)解题报告
- LeetCode解题报告 100. Same Tree [easy]
- 【LeetCode】234.Palindrome Linked List(Easy)解题报告
- 【LeetCode】118.Pascal's Triangle(easy)解题报告
- 【LeetCode】447.Number of Boomerangs(Easy)解题报告
- LeetCode解题报告 104. Maximum Depth of Binary Tree [easy]
- 【LeetCode】455.Assign Cookies(Easy)解题报告
- 【LeetCode】599.Minimum Index Sum of Two Lists(Easy)解题报告
- Leetcode 112. Path Sum 路径和 解题报告
- 【LeetCode】100.Same Tree(Easy)解题报告
- LeetCode解题报告 111. Minimum Depth of Binary Tree [easy]
- 【LeetCode】572.Subtree of Another Tree(Easy)解题报告
- 【LeetCode】270.Closest Binary Search Tree Value(Easy)解题报告
- 【LeetCode】119.Pascal's Triangle II(Easy)解题报告
- 【LeetCode】169. Majority Element(Easy)解题报告
- 【LeetCode】401.Binary Watch(easy)解题报告
- 【LeetCode】160.Intersection of Two Linked Lists(Easy)解题报告
- LeetCode解题报告 383. Ransom Note [easy]
- 【LeetCode】235.Lowest Common Ancestor of a Binary Search Tree(Easy)解题报告