题目:
给你二叉树的根节点 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;
}
};
该博客介绍了一种在二叉树中查找从根节点到叶子节点且节点值之和等于给定目标和的方法。通过使用栈进行深度优先搜索,遍历每个节点并更新路径总和,当找到一个没有子节点的叶子节点且其路径和等于目标和时返回true,否则继续搜索。
547

被折叠的 条评论
为什么被折叠?



