mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 03:34:02 +08:00
添加(0404.左叶子之和.md):增加typescript版本
This commit is contained in:
@ -372,6 +372,50 @@ var sumOfLeftLeaves = function(root) {
|
|||||||
};
|
};
|
||||||
```
|
```
|
||||||
|
|
||||||
|
## TypeScript
|
||||||
|
|
||||||
|
> 递归法
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
function sumOfLeftLeaves(root: TreeNode | null): number {
|
||||||
|
if (root === null) return 0;
|
||||||
|
let midVal: number = 0;
|
||||||
|
if (
|
||||||
|
root.left !== null &&
|
||||||
|
root.left.left === null &&
|
||||||
|
root.left.right === null
|
||||||
|
) {
|
||||||
|
midVal = root.left.val;
|
||||||
|
}
|
||||||
|
let leftVal: number = sumOfLeftLeaves(root.left);
|
||||||
|
let rightVal: number = sumOfLeftLeaves(root.right);
|
||||||
|
return midVal + leftVal + rightVal;
|
||||||
|
};
|
||||||
|
```
|
||||||
|
|
||||||
|
> 迭代法
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
function sumOfLeftLeaves(root: TreeNode | null): number {
|
||||||
|
let helperStack: TreeNode[] = [];
|
||||||
|
let tempNode: TreeNode;
|
||||||
|
let sum: number = 0;
|
||||||
|
if (root !== null) helperStack.push(root);
|
||||||
|
while (helperStack.length > 0) {
|
||||||
|
tempNode = helperStack.pop()!;
|
||||||
|
if (
|
||||||
|
tempNode.left !== null &&
|
||||||
|
tempNode.left.left === null &&
|
||||||
|
tempNode.left.right === null
|
||||||
|
) {
|
||||||
|
sum += tempNode.left.val;
|
||||||
|
}
|
||||||
|
if (tempNode.right !== null) helperStack.push(tempNode.right);
|
||||||
|
if (tempNode.left !== null) helperStack.push(tempNode.left);
|
||||||
|
}
|
||||||
|
return sum;
|
||||||
|
};
|
||||||
|
```
|
||||||
|
|
||||||
## Swift
|
## Swift
|
||||||
|
|
||||||
|
Reference in New Issue
Block a user