Skip to content

Commit 476496e

Browse files
committed
feat: add question 1325
1 parent e1d15da commit 476496e

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
/**
2+
* 1. DFS 判断当前节点是否为要删除的叶子节点, 是则返回 true, 否则返回 false
3+
* 2. 判断左右子节点删除情况, 如果都删除了, 则自身变为叶子节点, 再做一遍第1步判断
4+
*/
5+
6+
/**
7+
* Definition for a binary tree node.
8+
* function TreeNode(val) {
9+
* this.val = val;
10+
* this.left = this.right = null;
11+
* }
12+
*/
13+
/**
14+
* @param {TreeNode} root
15+
* @param {number} target
16+
* @return {TreeNode}
17+
*/
18+
var removeLeafNodes = function(root, target) {
19+
function dfs(node) {
20+
if (!node.left && !node.right) {
21+
return node.val === target;
22+
}
23+
24+
25+
if (node.left && dfs(node.left)) {
26+
node.left = null;
27+
}
28+
if (node.right && dfs(node.right)) {
29+
node.right = null;
30+
}
31+
32+
if (!node.left && !node.right) {
33+
return node.val === target;
34+
}
35+
return false;
36+
}
37+
38+
if (dfs(root)) {
39+
return null;
40+
}
41+
return root;
42+
};

0 commit comments

Comments
 (0)