diff --git a/problems/0112.路径总和.md b/problems/0112.路径总和.md index 41463ec1..6433996c 100644 --- a/problems/0112.路径总和.md +++ b/problems/0112.路径总和.md @@ -1006,6 +1006,63 @@ func traversal(_ cur: TreeNode?, count: Int) { } ``` +## C +0112.路径总和 +递归法: +```c +bool hasPathSum(struct TreeNode* root, int targetSum){ + // 递归结束条件:若当前节点不存在,返回false + if(!root) + return false; + // 若当前节点为叶子节点,且targetSum-root的值为0。(当前路径上的节点值的和满足条件)返回true + if(!root->right && !root->left && targetSum == root->val) + return true; + + // 查看左子树和右子树的所有节点是否满足条件 + return hasPathSum(root->right, targetSum - root->val) || hasPathSum(root->left, targetSum - root->val); +} +``` + +迭代法: +```c +// 存储一个节点以及当前的和 +struct Pair { + struct TreeNode* node; + int sum; +}; + +bool hasPathSum(struct TreeNode* root, int targetSum){ + struct Pair stack[1000]; + int stackTop = 0; + + // 若root存在,则将节点和值封装成一个pair入栈 + if(root) { + struct Pair newPair = {root, root->val}; + stack[stackTop++] = newPair; + } + + // 当栈不为空时 + while(stackTop) { + // 出栈栈顶元素 + struct Pair topPair = stack[--stackTop]; + // 若栈顶元素为叶子节点,且和为targetSum时,返回true + if(!topPair.node->left && !topPair.node->right && topPair.sum == targetSum) + return true; + + // 若当前栈顶节点有左右孩子,计算和并入栈 + if(topPair.node->left) { + struct Pair newPair = {topPair.node->left, topPair.sum + topPair.node->left->val}; + stack[stackTop++] = newPair; + } + if(topPair.node->right) { + struct Pair newPair = {topPair.node->right, topPair.sum + topPair.node->right->val}; + stack[stackTop++] = newPair; + } + } + return false; +} +``` + -----------------------