题目
题解
深度优先
递归:
class Solution {
public boolean hasPathSum(TreeNode root, int targetSum) {
if (root == null) {
return 0 == targetSum;
}
if (root.left != null && root.right != null) {
return hasPathSum(root.left, targetSum - root.val) || hasPathSum(root.right, targetSum - root.val);
}
if (root.left != null) {
return hasPathSum(root.left, targetSum - root.val);
}
if (root.right != null) {
return hasPathSum(root.right, targetSum - root.val);
}
return targetSum == root.val;
}
}
官方递归:
class Solution {
public boolean hasPathSum(TreeNode root, int sum) {
if (root == null) {
return false;
}
if (root.left == null && root.right == null) {
return sum == root.val;
}
return hasPathSum(root.left, sum - root.val) || hasPathSum(root.right, sum - root.val);
}
}
非递归:
class Solution {
public boolean hasPathSum(TreeNode root, int targetSum) {
Stack<TreeNode> stack = new Stack<>();
while (root != null || !stack.isEmpty()) {
if (root != null) {
stack.push(root);
if (root.left != null) {
root.left.val += root.val;
}
root = root.left;
} else {
root = stack.pop();
if (root.right == null && root.left == null) {
if (root.val == targetSum) {
return true;
}
}
if (root.right != null) {
root.right.val += root.val;
}
root = root.right;
}
}
return false;
}
}
广度优先:
值继承:
class Solution {
public boolean hasPathSum(TreeNode root, int targetSum) {
if (root == null) {
return false;
}
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
while (!queue.isEmpty()) {
TreeNode node = queue.poll();
if (node.right != null) {
node.right.val += node.val;
queue.add(node.right);
}
if (node.left != null) {
node.left.val += node.val;
queue.add(node.left);
}
if (node.left == null && node.right == null) {
if (node.val == targetSum) {
return true;
}
}
}
return false;
}
}