LeetCode 112.路径总和
题目链接:https://leetcode.cn/problems/path-sum/
题目
解答
递归法
从count
开始做减法而不是从0开始做加法
class Solution {
public:
bool traversal(TreeNode* cur, int count){
//到叶子节点且count为0,即找到了一条路径
if(!cur->left && !cur->right && count == 0){
return true;
}
//到叶子节点但是count不为0
if(!cur->left && !cur->right){
return false;
}
if(cur->left){
count -= cur->left->val;
if(traversal(cur->left,count)) return true;
count += cur->left->val;//回溯
}
if(cur->right){
count -= cur->right->val;
if(traversal(cur->right,count)) return true;
count += cur->right->val;//回溯
}
return false;
}
bool hasPathSum(TreeNode* root, int targetSum) {
if(root == NULL) return false;
return traversal(root,targetSum - root->val);
}
};
迭代法
使用栈模拟递归。
此时栈内的一个元素不仅要记录该节点的指针,还要记录从头节点到该节点的路径数值的总和。
将栈内的一个元素定义为pair<Treenode*,int>
,pair<节点指针,路径数值>
class Solution {
public:
bool hasPathSum(TreeNode* root, int targetSum) {
if(root == NULL) return false;
stack<pair<TreeNode*, int>> st;
st.push(pair<TreeNode*, int>(root, root->val));
while(!st.empty()){
pair<TreeNode*, int> node = st.top();
st.pop();
if(!node.first->left && !node.first->right && targetSum == node.second){
return true;
}
if(node.first->left){
st.push(pair<TreeNode*, int>(node.first->left,node.second + node.first->left->val));
}
if(node.first->right){
st.push(pair<TreeNode*, int>(node.first->right,node.second + node.first->right->val));
}
}
return false;
}
};