剑指 Offer II 047. 二叉树剪枝(814. 二叉树剪枝)
题目:
思路:
【1】利用递归的方式(在这种情况下其实递归比其他操作都要简单,当然广度也是可以做的,不过遍历次数需要两倍,如先取出来存入数组中,然后再倒序的方式进行删除)
代码展示:
简化:
//时间0 ms击败100% //内存38.9 MB击败84.18% class Solution { public TreeNode pruneTree(TreeNode root) { if (root == null) { 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; } }
利用递归的方式:
//时间0 ms击败100% //内存39.2 MB击败37.63% /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */ class Solution { public TreeNode pruneTree(TreeNode root) { dfs(root); //当是[0,null,0,0,0]这种的时候其实会全部剪掉 if (root != null && root.val == 0 && root.left == null && root.right == null) return null; return root; } public void dfs(TreeNode root) { if (root == null) return; dfs(root.left); dfs(root.right); if (root.left != null && root.left.val == 0 && root.left.left == null && root.left.right == null) root.left = null; if (root.right != null && root.right.val == 0 && root.right.left == null && root.right.right == null) root.right = null; } }