題目描述:
解題思路:遞歸,在節點是否滿足刪除條件,若不滿足,進行遞歸,之後再進行判斷其是否滿足刪除條件(因爲遞歸可能會刪除其左右子樹),刪除方法:令該節點等於父節點的子節點,調用方法,返回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; } }