添加 0404.左叶子之和.md C语言解法

This commit is contained in:
243wresfdxvc
2022-05-10 23:04:35 +00:00
parent 3ec08f41dd
commit 0e5e657a6d

View File

@ -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;
}
```
-----------------------