在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★ Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum. Note: A leaf is a node with no children. Example: Given the below binary tree and 5 / \ 4 8 / / \ 11 13 4 / \ \ 7 2 1 return true, as there exist a root-to-leaf path 给定一个二叉树和一个目标和,判断该树中是否存在根节点到叶子节点的路径,这条路径上所有节点值相加等于目标和。 说明: 叶子节点是指没有子节点的节点。 示例: 5 / \ 4 8 / / \ 11 13 4 / \ \ 7 2 1 返回 1 /** 2 * Definition for a binary tree node. 3 * public class TreeNode { 4 * public var val: Int 5 * public var left: TreeNode? 6 * public var right: TreeNode? 7 * public init(_ val: Int) { 8 * self.val = val 9 * self.left = nil 10 * self.right = nil 11 * } 12 * } 13 */ 14 class Solution { 15 func hasPathSum(_ root: TreeNode?, _ sum: Int) -> Bool { 16 if root == nil {return false} 17 return check(root,0,sum) 18 } 19 func check(_ node:TreeNode?,_ sum:Int,_ cur:Int)->Bool 20 { 21 if node == nil && sum == cur 22 { 23 return true 24 } 25 if node == nil 26 { 27 return false 28 } 29 if node!.left == nil && node!.right != nil 30 { 31 return check(node!.right,sum+node!.val,cur) 32 } 33 if node!.left != nil && node!.right == nil 34 { 35 return check(node!.left,sum+node!.val,cur) 36 } 37 return check(node!.left,sum + node!.val, cur) 38 || check(node!.right,sum + node!.val, cur) 39 } 40 } 36ms 1 /** 2 * Definition for a binary tree node. 3 * public class TreeNode { 4 * public var val: Int 5 * public var left: TreeNode? 6 * public var right: TreeNode? 7 * public init(_ val: Int) { 8 * self.val = val 9 * self.left = nil 10 * self.right = nil 11 * } 12 * } 13 */ 14 class Solution { 15 func hasPathSum(_ root: TreeNode?, _ sum: Int) -> Bool { 16 if root?.left == nil, root?.right == nil { // 叶节点或空节点 17 guard root != nil else { 18 return false 19 } 20 return sum == root!.val ? true : false 21 } 22 return hasPathSum(root?.left, sum - root!.val) || hasPathSum(root?.right, sum - root!.val) 23 } 24 } 28ms 1 /** 2 * Definition for a binary tree node. 3 * public class TreeNode { 4 * public var val: Int 5 * public var left: TreeNode? 6 * public var right: TreeNode? 7 * public init(_ val: Int) { 8 * self.val = val 9 * self.left = nil 10 * self.right = nil 11 * } 12 * } 13 */ 14 class Solution { 15 func hasPathSum(_ root: TreeNode?, _ sum: Int) -> Bool { 16 17 guard let root = root else { return false } 18 19 let difference = sum - root.val 20 if difference == 0 && root.left == nil && root.right == nil { 21 return true 22 } else { 23 return hasPathSum(root.left, difference) || hasPathSum(root.right, difference) 24 } 25 26 return false 27 } 28 }
|
请发表评论