题目描述:
LeetCode--二叉树剪枝
LeetCode--二叉树剪枝
解题思路:递归,在节点是否满足删除条件,若不满足,进行递归,之后再进行判断其是否满足删除条件(因为递归可能会删除其左右子树),删除方法:令该节点等于父节点的子节点,调用方法,返回null即将该节点置为null。

class Solution {
   public TreeNode pruneTree(TreeNode root) {
        if(root == null){
            return null;
        }
        else {
            if(root.left == null && root.right == null && root.val == 0){
                return null;
            }
            root.left = pruneTree(root.left);
            root.right = pruneTree(root.right);
            if(root.left == null && root.right == null && root.val == 0){
                return null;
            }

        }
        return root;
    }
}

相关文章:

  • 2022-01-17
  • 2021-06-28
  • 2021-06-13
  • 2021-12-21
  • 2021-12-25
  • 2021-05-10
猜你喜欢
  • 2022-12-23
  • 2021-12-31
  • 2022-12-23
  • 2021-08-24
  • 2021-05-23
  • 2022-12-23
  • 2021-10-18
相关资源
相似解决方案