题目地址:
https://www.lintcode.com/problem/path-sum/description
给定一棵二叉树,再给定一个数 x x x,问是否存在一条从树根到树叶的路径使得其路径和恰好等于 x x x。
如果树空返回false,如果本身就是树叶则返回树叶值是否等于给定值,否则在左右子树里寻找是否存在路径和等于 x x x减去树根。代码如下:
public class Solution {
/**
* @param root: the tree
* @param sum: the sum
* @return: if the tree has a root-to-leaf path
*/
public boolean pathSum(TreeNode root, int sum) {
// Write your code here.
if (root == null) {
return false;
}
if (root.left == null && root.right == null) {
return root.val == sum;
}
return pathSum(root.left, sum - root.val) || pathSum(root.right, sum - root.val);
}
}
class TreeNode {
int val;
TreeNode left, right;
public TreeNode(int val) {
this.val = val;
}
}
时间复杂度 O ( n ) O(n) O(n),空间 O ( h ) O(h) O(h)。