中级农民
- 积分
- 121
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2019-3-20
- 最后登录
- 1970-1-1
|
- public int getMaxIslandsAfterDeletion(TreeNode root) {
- return dfs(root, 0);
- }
- // otherIslandsLeft means if node were deleted, how many other islands above node will survive
- public int dfs(TreeNode node, int otherIslandsLeft) {
- int best = otherIslandsLeft;
- // because both node exist, therefore no matter which child is deleted (by definition, I will
- // also be removed), the other child node will survive
- if (node.left != null && node.right != null) {
- best = Math.max(best, otherIslandsLeft + 2);
- best = Math.max(best, dfs(node.left, otherIslandsLeft + 1));
- best = Math.max(best, dfs(node.right, otherIslandsLeft + 1));
- } else if (node.left != null && node.right == null) {
- best = Math.max(best, otherIslandsLeft + 1);
- best = Math.max(best, dfs(node.left, otherIslandsLeft));
- } else if (node.left == null && node.right != null) {
- best = Math.max(best, otherIslandsLeft + 1);
- best = Math.max(best, dfs(node.right, otherIslandsLeft));
- } // otherwise, null, null, do nothing
- return best;
- }
复制代码 |
|