复盘: 遗漏root节点为空的判断
效率不够高 , 如何优化?
Leetcode Path sumpesudo 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
}
}
}
网友评论