Skip to content

814.二叉树剪枝

https://leetcode.cn/problems/pOCWxh/description/

md
给定一个二叉树 根节点 root ,树的每个节点的值要么是 0,要么是 1。请剪除该二叉树中所有节点的值为 0 的子树。

节点 node 的子树为 node 本身,以及所有 node 的后代。

 

示例 1:

输入: [1,null,0,0,1]
输出: [1,null,0,null,1] 
解释: 
只有红色节点满足条件“所有不包含 1 的子树”。
右图为返回的答案。


示例 2:

输入: [1,0,1,0,0,0,1]
输出: [1,null,1,null,1]
解释: 


示例 3:

输入: [1,1,0,1,1,0,1,0]
输出: [1,1,0,1,1,null,1]
解释:

就是递归遍历, 通过nil/null等等, 来覆盖value来实现剪枝

go
/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func pruneTree(root *TreeNode) *TreeNode {

	// 判断是0的时候直接减少就行了
	if root == nil {
		return root
	}

	var trea func(node *TreeNode) *TreeNode

	trea = func(node *TreeNode) *TreeNode {

		if node == nil {
			return nil
		}

		node.Left = trea(node.Left) // 覆盖收缩, 收缩每一个节点为0的值
		node.Right = trea(node.Right)

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

		return node
	}
	return trea(root)
}
本站访客数 人次 本站总访问量