Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions src/main/java/com/leetcode/easy/PathSum112.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
// Tags: Tree, DFS
package com.leetcode.easy;

import com.leetcode.datastructure.TreeNode;

public class PathSum112 {
/**
* Time complexity: we visit each node exactly once,
* thus the time complexity is O(N), where N is the number of nodes.
* <p>
* Space complexity: in the worst case,
* the tree is completely unbalanced,
* e.g. each node has only one child node,
* the recursion call would occur N times (the height of the tree),
* therefore the storage to keep the call stack would be O(N).
*/
public boolean hasPathSum(TreeNode root, int targetSum) {
if (root == null) {
return false;
}
if (root.left == null && root.right == null && root.val == targetSum) {
return true;
}
return this.hasPathSum(root.left, targetSum - root.val) || this.hasPathSum(root.right, targetSum - root.val);
}
}
61 changes: 61 additions & 0 deletions src/test/java/com/leetcode/easy/PathSum112Test.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
package com.leetcode.easy;

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

import com.leetcode.datastructure.TreeNode;

import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;

public class PathSum112Test {
private PathSum112 solution;

@BeforeEach
void setUp() {
solution = new PathSum112();
}

@Test
void testHasPathSum_Example1() {
TreeNode root = new TreeNode(5);
root.left = new TreeNode(4);
root.right = new TreeNode(8);
root.left.left = new TreeNode(11);
root.left.left.left = new TreeNode(7);
root.left.left.right = new TreeNode(2);
root.right.left = new TreeNode(13);
root.right.right = new TreeNode(4);
root.right.right.right = new TreeNode(1);

int targetSum = 22;

boolean result = solution.hasPathSum(root, targetSum);

assertTrue(result);
}

@Test
void testHasPathSum_Example2() {
TreeNode root = new TreeNode(1);
root.left = new TreeNode(2);
root.right = new TreeNode(3);

int targetSum = 5;

boolean result = solution.hasPathSum(root, targetSum);

assertFalse(result);
}

@Test
void testHasPathSum_Example3() {
TreeNode root = null;

int targetSum = 0;

boolean result = solution.hasPathSum(root, targetSum);

assertFalse(result);
}
}
Loading