覆盤: 遺漏root節點為空的判斷
效率不夠高 , 如何優化?
pesudo code:
hasPathSum(node,sum)
if node is leaf and node.val-sum=0
return true
elseif node is leaf and node.val-sum!=0
return false
else
res1=false
res2=false
if node.left
res1= hasPathSum(node.left,sum-node.val)
if node.right
res2=hasPathSum(node.right,sum-node.val)
if res1||res2
return true
else
return false
go implementation :
func hasPathSum(root *TreeNode, sum int) bool {
return hasPathSumCustom(root, sum)
}
func hasPathSumCustom(node *TreeNode, sum int) bool {
if node == nil {
return false
}
if node.Left == nil && node.Right == nil && node.Val-sum == 0 {
return true
} else if node.Left == nil && node.Right == nil && node.Val-sum != 0 {
return false
} else {
res1 := false
res2 := false
if node.Left != nil {
res1 = hasPathSumCustom(node.Left, sum-node.Val)
}
if node.Right != nil {
res2 = hasPathSumCustom(node.Right, sum-node.Val)
}
if res1 || res2 {
return true
} else {
return false
}
}
}
本作品採用《CC 協議》,轉載必須註明作者和本文連結