-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDeleteLeavesWithGivenValue.java
More file actions
40 lines (34 loc) · 1.29 KB
/
DeleteLeavesWithGivenValue.java
File metadata and controls
40 lines (34 loc) · 1.29 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
package solutions;
import datastructure.TreeNode;
// [Problem] https://leetcode.com/problems/delete-leaves-with-a-given-value
class DeleteLeavesWithGivenValue {
// Recursion
// O(n) time, O(h) space where h = height
public TreeNode removeLeafNodes(TreeNode node, int target) {
if (node == null) {
return null;
}
node.left = removeLeafNodes(node.left, target);
node.right = removeLeafNodes(node.right, target);
if (isLeafNode(node) && node.val == target) {
return null;
}
return node;
}
private boolean isLeafNode(TreeNode node) {
return node.left == null && node.right == null;
}
// Test
public static void main(String[] args) {
DeleteLeavesWithGivenValue solution = new DeleteLeavesWithGivenValue();
TreeNode input = new TreeNode(1,
new TreeNode(2, new TreeNode(2), null),
new TreeNode(3, new TreeNode(2), new TreeNode(4)));
int target = 2;
TreeNode expectedOutput = new TreeNode(1,
null,
new TreeNode(3, null, new TreeNode(4)));
TreeNode actualOutput = solution.removeLeafNodes(input, target);
System.out.println("Test passed? " + expectedOutput.equals(actualOutput));
}
}