🚩传送门:牛客题目
题目
有一棵有个节点的二叉树,其根节点为
。
修剪规则如下:
- 修剪掉当前二叉树的叶子节点,但是不能直接删除叶子节点
- 只能修剪叶子节点的父节点,修剪了父节点之后,叶子节点也会对应删掉
- 如果想在留下尽可能多的节点前提下,修剪掉所有的叶子节点。请你返回修剪后的二叉树。
有如下二叉树,修剪过后仅会留下根节点。
示例1
输入:{1,#,1,#,1,#,1,#,1} 返回值:{1,#,1,#,1}
解题思路:递归
算法流程:
- 如果当前结点是空的,返回
_null_
- 如果当前结点非空,看左孩子是不是叶子结点
- 如果当前结点非空,看右孩子是不是叶子结点
- 递归左右子树
- 返回
_root_
我的代码
public class Solution {
public TreeNode pruneLeaves(TreeNode root) {
// 当前结点空的
if (root == null) return null;
// 左孩子叶子结点
if (root.left != null && root.left.left == null && root.left.right == null) return null;
// 右孩子叶子结点
if (root.right != null && root.right.left == null && root.right.right == null) return null;
root.left = pruneLeaves(root.left);
root.right = pruneLeaves(root.right);
return root;
}
}