mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 08:50:15 +08:00
update 0404.左叶子之和: 修改 go 代码,优化 js 代码风格
This commit is contained in:
@ -35,7 +35,7 @@
|
||||
|
||||

|
||||
|
||||
相信通过这两个图,大家可以最左叶子的定义有明确理解了。
|
||||
相信通过这两个图,大家对最左叶子的定义有明确理解了。
|
||||
|
||||
那么**判断当前节点是不是左叶子是无法判断的,必须要通过节点的父节点来判断其左孩子是不是左叶子。**
|
||||
|
||||
@ -298,48 +298,49 @@ class Solution:
|
||||
|
||||
```go
|
||||
func sumOfLeftLeaves(root *TreeNode) int {
|
||||
var res int
|
||||
findLeft(root,&res)
|
||||
return res
|
||||
if root == nil {
|
||||
return 0
|
||||
}
|
||||
func findLeft(root *TreeNode,res *int){
|
||||
//左节点
|
||||
leftValue := sumOfLeftLeaves(root.Left) // 左
|
||||
|
||||
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)
|
||||
leftValue = root.Left.Val // 中
|
||||
}
|
||||
|
||||
rightValue := sumOfLeftLeaves(root.Right) // 右
|
||||
|
||||
return leftValue + rightValue
|
||||
}
|
||||
```
|
||||
|
||||
**迭代法**
|
||||
**迭代法(前序遍历)**
|
||||
|
||||
```go
|
||||
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
|
||||
st := make([]*TreeNode, 0)
|
||||
if root == nil {
|
||||
return 0
|
||||
}
|
||||
if node.Left!=nil{
|
||||
queue.PushBack(node.Left)
|
||||
st = append(st, root)
|
||||
result := 0
|
||||
|
||||
for len(st) != 0 {
|
||||
node := st[len(st)-1]
|
||||
st = st[:len(st)-1]
|
||||
if node.Left != nil && node.Left.Left == nil && node.Left.Right == nil {
|
||||
result += node.Left.Val
|
||||
}
|
||||
if node.Right != nil {
|
||||
queue.PushBack(node.Right)
|
||||
st = append(st, node.Right)
|
||||
}
|
||||
if node.Left != nil {
|
||||
st = append(st, node.Left)
|
||||
}
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
return res
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
|
||||
|
Reference in New Issue
Block a user