//

给你一棵以节点 0 为根节点的树,定义如下:

// // // //

请你删除节点值之和为 0 的每一棵子树。

// //

在完成所有删除之后,返回树中剩余节点的数目。

// //

 

// //

示例 1:

// //

// //
输入:nodes = 7, parent = [-1,0,0,1,2,2,2], value = [1,-2,4,0,-2,-1,-1]
//输出:2
//
// //

示例 2:

// //
输入:nodes = 7, parent = [-1,0,0,1,2,2,2], value = [1,-2,4,0,-2,-1,-2]
//输出:6
//
// //

示例 3:

// //
输入:nodes = 5, parent = [-1,0,1,0,0], value = [-672,441,18,728,378]
//输出:5
//
// //

示例 4:

// //
输入:nodes = 5, parent = [-1,0,0,1,1], value = [-686,-842,616,-739,-746]
//输出:5
//
// //

 

// //

提示:

// // //
Related Topics
  • 深度优先搜索
  • 广度优先搜索

  • 👍 32
  • 👎 0
  • package leetcode.editor.cn; import java.util.ArrayList; import java.util.List; // 1273:删除树节点 public class DeleteTreeNodes { public static void main(String[] args) { Solution solution = new DeleteTreeNodes().new Solution(); // TO TEST } //leetcode submit region begin(Prohibit modification and deletion) class Solution { public int deleteTreeNodes(int nodes, int[] parent, int[] value) { List> lists = new ArrayList<>(); for (int i = 0; i < nodes; i++) { lists.add(new ArrayList<>()); } int head = 0; for (int i = 0; i < parent.length; i++) { if (parent[i] == -1) { head = i; continue; } lists.get(parent[i]).add(i); } int[] tmp = dfs(lists, head, value); return tmp[0] == 0 ? 0 : tmp[1]; } private int[] dfs(List> lists, int index, int[] value) { int[] cur = new int[]{value[index], 1}; List list = lists.get(index); int size = list.size(); if (size == 0) { return cur; } for (Integer indx : list) { int[] tmp = dfs(lists, indx, value); if (tmp[0] != 0) { cur[0] += tmp[0]; cur[1] += tmp[1]; } } return cur; } } //leetcode submit region end(Prohibit modification and deletion) }