问题描述 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 : 地址 问题分析 找二叉树中是否存在一条路径和为sum的路径。同LeetCode 111. Minimum Depth of Binary Tree 这题最大的坑便是递归终止条件的判断。 因为路径是要求从根到叶子节点,如果我们选取空结点为递归终止条件的话,那么找的的不一定是到叶子节点的路径。所以应当选取叶子节点为递归终止条件。 经验教训 对于递归终止条件的选择,一定不要想当然 。 代码实现 减法思想 public boolean hasPathSum(TreeNode root, int sum) { if (root == null) { return false; } if (root.left == null && root.right == null) { return root.val == sum; } return hasPathSum(root.left, sum - root.val) || hasPathSum(root.right, sum - root.val); } 加法思想 public boolean findPath(TreeNode root, int curSum, int target) { if (root == null) { return false; } if (root.left == null && root.right == null) { return curSum + root.val == target; } return findPath(root.left, curSum + root.val, target) || findPath(root.right, curSum + root.val, target); }