112. Path Sum
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.
题目链接:https://leetcode-cn.com/problems/path-sum/
思路
利用DFS的思想。
法一:非递归,栈
注意几个小陷阱:
1)树中有负数,因此一定要走到叶节点才能判定最后sum是否符合要求,无法在中途提前结束sum的计算。
特殊样例:
[-2,null,-3]
-5
2)由于sum的值是逐层累加的,因此在回溯时,也要逐层减去每个父节点的值,不能像普通的树遍历那样,跨层回到上一节点。在出栈时不能立刻弹出元素,若还需要再次取同一元素的话,可以加一个用于标记的空节点来帮助判断是否第一次取出。
特殊样例:
[1,-2,-3,1,3,-2,null,-1]
3
代码:
/**
* 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;
stack<TreeNode*> q;
q.push(root);
int cur = 0;
while(!q.empty()){
auto tmp = q.top();
if(!tmp){
q.pop();
cur -= (q.top()->val);
q.pop();
continue;
}
cur += (tmp->val);
if(!tmp->left && !tmp->right){
if(cur==sum) return true;
else{
cur -= (tmp->val);
q.pop();
continue;
}
}
else{
q.push(NULL);
if(tmp->right) q.push(tmp->right);
if(tmp->left) q.push(tmp->left);
}
}
return false;
}
};
法二:递归
一开始思考递归想了五分钟也没想出来,一直想要找个办法把根节点到当前的累计sum向下传递 or 向上回传。后来做完非递归,突然就想到了,其实不用传递累计sum,可以在向下递归的时候改变参数sum😂,也不知道是不是受了非递归的启发。
当然,非递归方法不管是计算sum还是改变参数sum,总体思路还是一样的,需要用栈逐层回溯,没啥区别。
注意一个特殊样例:
[]
0
这使得终止递归的条件不能是root==NULL,而是root==叶子节点。
/**
* 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){
if(sum==root->val) return true;
else return false;
}
sum -= (root->val);
return (hasPathSum(root->left, sum) || hasPathSum(root->right, sum));
}
};