mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-10 20:40:39 +08:00
添加 404.左叶子之和 Javascript版本
添加 404.左叶子之和 Javascript版本
This commit is contained in:
@ -226,6 +226,71 @@ class Solution:
|
|||||||
```
|
```
|
||||||
Go:
|
Go:
|
||||||
|
|
||||||
|
> 递归法
|
||||||
|
|
||||||
|
```go
|
||||||
|
/**
|
||||||
|
* Definition for a binary tree node.
|
||||||
|
* type TreeNode struct {
|
||||||
|
* Val int
|
||||||
|
* Left *TreeNode
|
||||||
|
* Right *TreeNode
|
||||||
|
* }
|
||||||
|
*/
|
||||||
|
func sumOfLeftLeaves(root *TreeNode) int {
|
||||||
|
var res int
|
||||||
|
findLeft(root,&res)
|
||||||
|
return res
|
||||||
|
}
|
||||||
|
func findLeft(root *TreeNode,res *int){
|
||||||
|
//左节点
|
||||||
|
if root.Left!=nil&&root.Left.Left==nil&&root.Left.Right==nil{
|
||||||
|
*res=*res+root.Left.Val
|
||||||
|
}
|
||||||
|
if root.Left!=nil{
|
||||||
|
findLeft(root.Left,res)
|
||||||
|
}
|
||||||
|
if root.Right!=nil{
|
||||||
|
findLeft(root.Right,res)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
> 迭代法
|
||||||
|
|
||||||
|
```go
|
||||||
|
/**
|
||||||
|
* Definition for a binary tree node.
|
||||||
|
* type TreeNode struct {
|
||||||
|
* Val int
|
||||||
|
* Left *TreeNode
|
||||||
|
* Right *TreeNode
|
||||||
|
* }
|
||||||
|
*/
|
||||||
|
func sumOfLeftLeaves(root *TreeNode) int {
|
||||||
|
var res int
|
||||||
|
queue:=list.New()
|
||||||
|
queue.PushBack(root)
|
||||||
|
for queue.Len()>0{
|
||||||
|
length:=queue.Len()
|
||||||
|
for i:=0;i<length;i++{
|
||||||
|
node:=queue.Remove(queue.Front()).(*TreeNode)
|
||||||
|
if node.Left!=nil&&node.Left.Left==nil&&node.Left.Right==nil{
|
||||||
|
res=res+node.Left.Val
|
||||||
|
}
|
||||||
|
if node.Left!=nil{
|
||||||
|
queue.PushBack(node.Left)
|
||||||
|
}
|
||||||
|
if node.Right!=nil{
|
||||||
|
queue.PushBack(node.Right)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return res
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
JavaScript:
|
JavaScript:
|
||||||
递归版本
|
递归版本
|
||||||
```javascript
|
```javascript
|
||||||
|
Reference in New Issue
Block a user