mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 02:53:31 +08:00
添加 0404.左叶子之和.md C语言解法
This commit is contained in:
@ -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;
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
-----------------------
|
||||
|
Reference in New Issue
Block a user