From 0e5e657a6d5ba057e8dfa77019b25c5404fe9a9b Mon Sep 17 00:00:00 2001 From: 243wresfdxvc Date: Tue, 10 May 2022 23:04:35 +0000 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200404.=E5=B7=A6=E5=8F=B6?= =?UTF-8?q?=E5=AD=90=E4=B9=8B=E5=92=8C.md=20C=E8=AF=AD=E8=A8=80=E8=A7=A3?= =?UTF-8?q?=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0404.左叶子之和.md | 49 ++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) diff --git a/problems/0404.左叶子之和.md b/problems/0404.左叶子之和.md index 6420da81..d7fd629e 100644 --- a/problems/0404.左叶子之和.md +++ b/problems/0404.左叶子之和.md @@ -466,6 +466,55 @@ func sumOfLeftLeaves(_ root: TreeNode?) -> Int { } ``` +## C +递归法: +```c +int sumOfLeftLeaves(struct TreeNode* root){ + // 递归结束条件:若当前结点为空,返回0 + if(!root) + return 0; + + // 递归取左子树的左结点和和右子树的左结点和 + int leftValue = sumOfLeftLeaves(root->left); + int rightValue = sumOfLeftLeaves(root->right); + + // 若当前结点的左结点存在,且其为叶子结点。取它的值 + int midValue = 0; + if(root->left && (!root->left->left && !root->left->right)) + midValue = root->left->val; + + return leftValue + rightValue + midValue; +} +``` + +迭代法: +```c +int sumOfLeftLeaves(struct TreeNode* root){ + struct TreeNode* stack[1000]; + int stackTop = 0; + + // 若传入root结点不为空,将其入栈 + if(root) + stack[stackTop++] = root; + + int sum = 0; + //若栈不为空,进行循环 + while(stackTop) { + // 出栈栈顶元素 + struct TreeNode *topNode = stack[--stackTop]; + // 若栈顶元素的左孩子为左叶子结点,将其值加入sum中 + if(topNode->left && (!topNode->left->left && !topNode->left->right)) + sum += topNode->left->val; + + // 若当前栈顶结点有左右孩子。将他们加入栈中进行遍历 + if(topNode->right) + stack[stackTop++] = topNode->right; + if(topNode->left) + stack[stackTop++] = topNode->left; + } + return sum; +} +``` -----------------------