题目:
给你二叉树的根节点 root 和一个表示目标和的整数 targetSum ,判断该树中是否存在 根节点到叶子节点 的路径,这条路径上所有节点值相加等于目标和 targetSum 。
叶子节点 是指没有子节点的节点。
示例:
输入:root = [5,4,8,11,null,13,4,7,2,null,null,null,1], targetSum = 22
输出:true
解法
代码
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 && node.second == targetSum) return true;
if (node.first->left) {
st.push(pair<TreeNode*, int>(node.first->left, node.first->left->val + node.second));
}
if (node.first->right) {
st.push(pair<TreeNode*, int>(node.first->right, node.first->right->val + node.second));
}
}
return false;
}
};