剑指 Offer II 047. 二叉树剪枝bb
| 2023-3-30
字数 254阅读时长 1 分钟
标签
二叉树
DFS
日期
Oct 16, 2022

剑指 Offer II 047. 二叉树剪枝

题目描述

给定一个二叉树 根节点 root ,树的每个节点的值要么是 0,要么是 1。请剪除该二叉树中所有节点的值为 0 的子树。节点 node的子树为 node本身,以及所有 node的后代。
示例 1:
notion image
输入: [1,null,0,0,1] 输出: [1,null,0,null,1] 解释: 只有红色节点满足条件“所有不包含 1 的子树”。 右图为返回的答案。

题目解析

思路:

  • 通过递归遍历左子树和右子树,剪枝的条件是该节点值为0且没有左子树和右子树,找出符合条件的节点return null并赋值实现剪枝

代码:

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; } }
Loading...
next