leetcode【112】Path Sum
程序员文章站
2024-01-05 11:23:40
...
问题描述:
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.
源码:
还是递归大法,时间69%,空间100%。
/**
* 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 && root->val == sum) return true;
bool res = false;
if(root->left) res |= hasPathSum(root->left, sum - root->val);
if(root->right) res |= hasPathSum(root->right, sum - root->val);
return res;
}
};
再来看看非递归的。
/**
* 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;
queue<pair<TreeNode*, int>> st;
st.push(make_pair(root, sum - root->val));
while(!st.empty()){
auto tmp = st.front();
// cout<<tmp.second<<endl;
st.pop();
if(tmp.second==0 && !tmp.first->left && !tmp.first->right) return true;
// if(tmp.second<=0) continue;
if(tmp.first->left) st.push(make_pair(tmp.first->left, tmp.second - tmp.first->left->val));
if(tmp.first->right) st.push(make_pair(tmp.first->right, tmp.second - tmp.first->right->val));
}
return false;
}
};
推荐阅读
-
leetcode【112】Path Sum
-
Leetcode算法刷题:第112题 Path Sum
-
leetcode(112):Path Sum
-
leetcode[112]Path Sum
-
LeetCode 112 Path Sum
-
Leetcode Two Sum (java)Longest Substring Without Repeating Characters
-
[LeetCode 4.18] Minimum Path Sum
-
POJ3126 Prime Path(BFS) 类似于Leetcode 单词接龙
-
LeetCode 15: 3Sum题解(python)
-
【LeetCode】Two Sum & Two Sum II - Input array is sorted & Two Sum IV - Input is a BST