题目描述
原题链接:112. 路径总和
解题思路
1、回溯法
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
bool hasPathSum(TreeNode* root, int targetSum) {
if(!root) return false;
// 当找到叶子结点而且整个路径和正好为targetSum时,返回true
if(!root->left && !root->right) {
if(targetSum - root->val == 0)
return true;
}
// 先找左子树,看有没有目标路径
bool res = hasPathSum(root->left, targetSum - root->val);
// 当还未找到时,才继续向下遍历
if(res == false) res = hasPathSum(root->right, targetSum - root->val);
return res;
}
};
精简版
**精简版**
```cpp
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
bool hasPathSum(TreeNode* root, int targetSum) {
if(!root) return false;
if(!root->left && !root->right) return targetSum - root->val == 0;
bool res = hasPathSum(root->left, targetSum - root->val);
if(res == false) res = hasPathSum(root->right, targetSum - root->val);
return res;
}
};
2、迭代法(先序遍历)
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
bool hasPathSum(TreeNode* root, int targetSum) {
if(!root) return false;
stack<int> res;
stack<TreeNode*> st;
st.push(root);
res.push(root->val);
while(!st.empty()) {
TreeNode* node = st.top(); st.pop();
int data = res.top(); res.pop();
if(!node->left && !node->right && data == targetSum)
return true;
if(node->left) {
st.push(node->left);
res.push(data + node->left->val);
}
if(node->right) {
st.push(node->right);
res.push(data + node->right->val);
}
}
return false;
}
};
参考文章:112. 路径总和