/** * Definition for singly-linked list. * type ListNode struct { * Val int * Next *ListNode * } */ /** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */ funcsortedListToBST(head *ListNode) *TreeNode { nodes := []int{} for p := head; p != nil; p = p.Next { nodes = append(nodes, p.Val) } return build(nodes, 0, len(nodes)-1) }
/** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */ var found bool var sum, target int funchasPathSum(root *TreeNode, targetSum int)bool { if root == nil { returnfalse } sum = 0 found = false target = targetSum traverse(root) return found }
functraverse(root *TreeNode) { if root == nil { return } sum += root.Val if root.Left == nil && root.Right == nil && sum == target { found = true } traverse(root.Left) traverse(root.Right) sum -= root.Val }
/** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */ var sum int var res [][]int funcpathSum(root *TreeNode, targetSum int) [][]int { res = [][]int{} sum = 0 if root == nil { return res } traverse(root, targetSum, []int{}) return res }