在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
func hasPathSum(root *TreeNode, sum int) bool { if root == nil{ return false } if root.Left==nil && root.Right == nil{ return root.Val == sum } return hasPathSum(root.Left,sum-root.Val) || hasPathSum(root.Right,sum-root.Val) } Leetcode 113:路径总和 II
func FindPath( root *TreeNode , expectNumber int ) [][]int { // write code here if root == nil{ return nil } res := make([][]int,0) path := []int{} getWay(root,path,expectNumber,&res) return res } func getWay(root *TreeNode, path []int,sum int,res *[][]int){ if root == nil { return } path = append(path, root.Val) if sum == root.Val && root.Left==nil && root.Right==nil{ // dst := make([]int,len(path)+1) *res = append(*res, path) } getWay(root.Left,path,sum-root.Val,res) getWay(root.Right,path,sum-root.Val,res) path = path[:len(path)-1] }
Leetcode 437:路径总和 III
func pathSum(root *TreeNode, sum int) int { if root == nil{ return 0 } return hasPath(root,sum,0)+pathSum(root.Left,sum)+pathSum(root.Right,sum) } func hasPath(root *TreeNode,sum,count int) int{ if root == nil{ return count } sum-=root.Val if 0 == sum { count++ } count = hasPath(root.Left,sum,count) count = hasPath(root.Right,sum,count) return count }
|
请发表评论