Skip to content

Commit e27be80

Browse files
committed
feat: Add solution for delete-leaves-with-a-given-value problem
1 parent eb5ac03 commit e27be80

File tree

1 file changed

+91
-0
lines changed

1 file changed

+91
-0
lines changed
Lines changed: 91 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,91 @@
1+
// Problem: https://leetcode.com/problems/delete-leaves-with-a-given-value/
2+
// Doc: https://leetcode.com/problems/delete-leaves-with-a-given-value/solutions/5504665/efficient-leaf-node-removal-in-a-binary-tree/
3+
class TreeNode {
4+
val: number;
5+
left: TreeNode | null;
6+
right: TreeNode | null;
7+
constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
8+
this.val = val === undefined ? 0 : val;
9+
this.left = left === undefined ? null : left;
10+
this.right = right === undefined ? null : right;
11+
}
12+
}
13+
14+
function removeLeafNodes(
15+
root: TreeNode | null,
16+
target: number
17+
): TreeNode | null {
18+
if (!root) return root;
19+
root.left = removeLeafNodes(root.left, target);
20+
root.right = removeLeafNodes(root.right, target);
21+
22+
if (root.val === target && !root.left && !root.right) {
23+
root = null;
24+
}
25+
26+
return root;
27+
}
28+
29+
const getValues = (root: TreeNode | null): (number | null)[] => {
30+
if (!root) return [null];
31+
32+
return [root.val, ...getValues(root.left), ...getValues(root.right)];
33+
};
34+
35+
describe('Delete Leaves With a Given Value', () => {
36+
it('#1 should remove leaf nodes with value 3', () => {
37+
const root = new TreeNode(
38+
1,
39+
new TreeNode(2, new TreeNode(2), null),
40+
new TreeNode(3, new TreeNode(2), new TreeNode(4))
41+
);
42+
const target = 3;
43+
44+
const result = removeLeafNodes(root, target);
45+
46+
const actual = getValues(result);
47+
const expected = getValues(
48+
new TreeNode(
49+
1,
50+
new TreeNode(2, new TreeNode(2), null),
51+
new TreeNode(3, new TreeNode(2), new TreeNode(4))
52+
)
53+
);
54+
55+
expect(actual).toEqual(expected);
56+
});
57+
58+
it('#2 should remove leaf nodes with value 1', () => {
59+
const root = new TreeNode(1, new TreeNode(1), new TreeNode(1));
60+
const target = 1;
61+
62+
const result = removeLeafNodes(root, target);
63+
64+
const actual = getValues(result);
65+
const expected = getValues(null);
66+
67+
expect(actual).toEqual(expected);
68+
});
69+
70+
it('#3 should remove leaf nodes with value 1', () => {
71+
const root = new TreeNode(
72+
1,
73+
new TreeNode(2, new TreeNode(2), null),
74+
new TreeNode(1, new TreeNode(2), new TreeNode(1))
75+
);
76+
const target = 1;
77+
78+
const result = removeLeafNodes(root, target);
79+
80+
const actual = getValues(result);
81+
const expected = getValues(
82+
new TreeNode(
83+
1,
84+
new TreeNode(2, new TreeNode(2), null),
85+
new TreeNode(1, new TreeNode(2), null)
86+
)
87+
);
88+
89+
expect(actual).toEqual(expected);
90+
});
91+
});

0 commit comments

Comments
 (0)