/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ classSolution{ publicbooleanhasPathSum(TreeNode root, int sum){ if (root == null) { returnfalse; } if (root.left == null && root.right == null) { return sum == root.val; } return hasPathSum(root.left, sum - root.val) || hasPathSum(root.right, sum - root.val); } }
Language: Go
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
/** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */ funchasPathSum(root *TreeNode, sum int)bool { if root == nil { returnfalse } if root.Left == nil && root.Right == nil { return root.Val == sum } return hasPathSum(root.Left, sum - root.Val) || hasPathSum(root.Right, sum - root.Val) }