/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
法一:递归
最简版:
class Solution {
public boolean hasPathSum(TreeNode root, int targetSum) {
if (root == null) return false;
//if (root.val == targetSum) return true;
//这一步在输入(1,2),1时错误,因为此时判断了root.val == targetSum,
//但是实际上结束判断时需要判断是否是叶子节点,只有当是叶子节点时,且
//最后一层的root.val == targetSum时才为true。
if (root.left == null && root.right == null && root.val == targetSum) return true;
return hasPathSum(root.left, targetSum - root.val) || hasPathSum(root.right, targetSum - root.val);
}
}
详细版:
class Solution {
public boolean hasPathSum(TreeNode root, int targetSum) {
if (root == null) {
return false;
}
targetSum -= root.val;
// 叶子结点
if (root.left == null && root.right == null) {
return targetSum == 0;
}
if (root.left != null) {
boolean left = hasPathSum(root.left, targetSum);
if (left) {// 已经找到
return true;
}
}
if (root.right != null) {
boolean right = hasPathSum(root.right, targetSum);
if (right) {// 已经找到
return true;
}
}
return false;
}
}
迭代:
class Solution {
public boolean hasPathSum(TreeNode root, int targetSum) {
if (root == null) return false;
Queue<TreeNode> queue = new LinkedList<>();
//需要一个容器盛放当前节点的值
Queue<Integer> queVal = new LinkedList<>();
queue.offer(root);
queVal.offer(root.val);
//int res = 0;
while (!queue.isEmpty()) {
TreeNode node = queue.poll();
int tem = queVal.poll();
//res += tem;
//当遍历到叶子节点时,判断是否与目标值相等,相等返回true,不相等继续进行,找其他的路径
if (node.left == null && node.right == null) {
if (tem == targetSum) {
return true;
}
continue;
}
if (node.left != null) {
queue.offer(node.left);
queVal.offer(node.left.val + tem);
}
if (node.right != null) {
queue.offer(node.right);
queVal.offer(node.right.val + tem);
}
}
return false;
}
}