路径总和
递归
class Solution {
public:
bool hasPathSum(TreeNode* root, int targetSum) {
if (!root) return false;
if (!root->left && !root->right && targetSum == root->val) return true;
return hasPathSum(root->left, targetSum - root->val) ||
hasPathSum(root->right, targetSum - root->val);
}
};
非递归
class Solution {
public:
bool hasPathSum(TreeNode* root, int targetSum) {
stack<TreeNode*> stk;
stack<int> pathSum;
if (!root) return false;
stk.push(root);
pathSum.push(root->val);
while(!stk.empty()) {
TreeNode* node = stk.top();
stk.pop();
if (node) {
if (node->right) stk.push(node->right);
if (node->left) stk.push(node->left);
stk.push(node);
stk.push(nullptr);
}
else {
node = stk.top();
stk.pop();
int now = pathSum.top();
pathSum.pop();
if (!node->left && !node->right)
if (now == targetSum) return true;
if (node->right) pathSum.push(now + node->right->val);
if (node->left) pathSum.push(now + node->left->val);
}
}
return false;
}
};