递归
/**
* 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)
return sum==root->val;
return hasPathSum(root->left,sum-root->val)||hasPathSum(root->right,sum-root->val);
}
};
迭代,还算简单,但是我这么写有点绕,用2个栈应该好一些
/**
* 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<pair<TreeNode*,int>> stk;
stk.push(make_pair(root,sum-root->val));
pair<TreeNode*,int> p;
while(!stk.empty()){
p=stk.top();
stk.pop();
if(!p.first->left && !p.first->right && p.second==0)
return true;
if(p.first->right) stk.push(make_pair(p.first->right,p.second-p.first->right->val));
if(p.first->left) stk.push(make_pair(p.first->left,p.second-p.first->left->val));
}
return false;
}
};