LeetCode 814. 二叉树剪枝

题目描述

814. 二叉树剪枝

思路分析

解法一:后序遍历剪枝(推荐)

核心思路

  • 后序遍历先处理左右子树。
  • 若子树不包含 1,则返回 null。
  • 当前节点为 0 且左右为空时删除。


复杂度分析

  • 时间复杂度:O(n),其中 n 表示节点数。
  • 空间复杂度:O(h),其中 h 为树高。
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;
    }
}
func pruneTree(root *TreeNode) *TreeNode {
	if root == nil {
		return nil
	}

	root.Left = pruneTree(root.Left)
	root.Right = pruneTree(root.Right)

	if root.Left == nil && root.Right == nil && root.Val == 0 {
		return nil
	}
	return root
}

相似题目

题目 难度 考察点
814. 二叉树剪枝 中等 后序遍历
1325. 删除给定值的叶子节点 中等 后序遍历
1110. 删点成林 中等 后序遍历
669. 修剪二叉搜索树 中等 递归
404. 左叶子之和 简单 DFS
687. 最长同值路径 中等 DFS
本文作者:
本文链接: https://hgnulb.github.io/blog/2025/74238316
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议,转载请注明出处!