class Solution {
public TreeNode pruneTree(TreeNode root) {
// dfs[root]
root = dfs(root);
return root;
}
public TreeNode dfs(TreeNode root) {
if (root != null) {
root.left = dfs(root.left);
root.right = dfs(root.right);
if (root.right == null && root.left == null && root.val == 0) {
return null;
}
} else {
return null;
}
return root;
}
}
想问一下大家,在pruneTree里,为什么必须root = dfs(root);,直接dfs(root)会有一个测试用例过不了。
[0,null,0,0,0],这个正常是[],但如果我直接dfs(root),答案是[0];而root = dfs(root)会得到正确答案。
首先4个0都是走了if里return null的,但的头节点与其他不同的是,它return后没人接(如果主函数仅仅是dfs[root])。
也就是说最后一个null没人接,所以没删掉头节点?为什么?
题目: