题意描述:
给你二叉树的根节点 root 和一个表示目标和的整数 targetSum 。判断该树中是否存在 根节点到叶子节点 的路径,这条路径上所有节点值相加等于目标和 targetSum 。如果存在,返回 true ;否则,返回 false 。
叶子节点 是指没有子节点的节点。
因为要判断是否存在这样一条路径使得总和为目标值,所以在递归的参数确定时,除需要定义节点外还要定义一个返回值,用来判断是否符合目标值。
不要去累加然后判断是否等于目标和,那么代码比较麻烦,可以用递减,让计数器count初始为目标和,然后每次减去遍历路径节点上的数值。
如果最后count == 0,同时到了叶子节点的话,说明找到了目标和。
如果遍历到了叶子节点,count不为0,就是没找到。
递归法:
C++代码如下:
class Solution {
private:
bool traversal(TreeNode* cur, int count){
if(!cur->left && !cur->right && count == 0){
return true;
}
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;
}
public:
bool hasPathSum(TreeNode* root, int targetSum) {
if(root == NULL){
return false;
}
return traversal(root, targetSum - root->val);
}
};
迭代法:
需要用pair结构来存放栈内的元素(指针和数值)
C++代码如下:
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->right){
st.push(pair<TreeNode*, int>(node.first->right, node.second + node.first->right->val));
}
if(node.first->left){
st.push(pair<TreeNode*, int>(node.first->left, node.second + node.first->left->val));
}
}
return false;
}
};