[LeetCode] 1973. Count Nodes Equal to Sum of Descendants

Given the root of a binary tree, return the number of nodes where the value of the node is equal to the sum of the values of its descendants.

A descendant of a node x is any node that is on the path from node x to some leaf node. The sum is considered to be 0 if the node has no descendants.

Example 1:

Input: root = [10,3,4,2,1]
Output: 2
Explanation:
For the node with value 10: The sum of its descendants is 3+4+2+1 = 10.
For the node with value 3: The sum of its descendants is 2+1 = 3.

Example 2:

Input: root = [2,3,null,2,null]
Output: 0
Explanation:
No node has a value that is equal to the sum of its descendants.

Example 3:

Input: root = [0]
Output: 1
For the node with value 0: The sum of its descendants is 0 since it has no descendants.

Constraints:

  • The number of nodes in the tree is in the range [1, 105].
  • 0 <= Node.val <= 105

找与子树节点值相等的节点。

题意是给一棵二叉树,请返回有多少个节点其节点值 = 由这个节点所有孩子节点值的和。

思路是后序遍历,类似1120题。因为要计算孩子节点的值,所以必然是后序遍历。对于当前节点来说,我们通过后序遍历计算了左孩子节点值 + 右孩子节点值,如果左孩子节点值 + 右孩子节点值 = 当前的节点值,那么我们就找到了一个符合题意的节点。对于当前节点,往其父节点返回的是以当前节点为父节点的子树的节点值的和。

时间O(n)

空间O(n)

Java实现

 1 /**
 2  * Definition for a binary tree node.
 3  * public class TreeNode {
 4  *     int val;
 5  *     TreeNode left;
 6  *     TreeNode right;
 7  *     TreeNode() {}
 8  *     TreeNode(int val) { this.val = val; }
 9  *     TreeNode(int val, TreeNode left, TreeNode right) {
10  *         this.val = val;
11  *         this.left = left;
12  *         this.right = right;
13  *     }
14  * }
15  */
16 class Solution {
17     int res = 0;
18     
19     public int equalToDescendants(TreeNode root) {
20         // corner case
21         if (root == null) {
22             return res;
23         }
24         helper(root);
25         return res;
26     }
27     
28     private int helper(TreeNode root) {
29         if (root == null) {
30             return 0;
31         }
32         int left = helper(root.left);
33         int right = helper(root.right);
34         int sum = left + right;
35         if (sum == root.val) {
36             res++;
37         }
38         return sum + root.val;
39     }
40 }

 

相关题目

1120. Maximum Average Subtree

1973. Count Nodes Equal to Sum of Descendants

LeetCode 题目总结

posted @ 2021-09-10 00:20  CNoodle  阅读(130)  评论(0编辑  收藏  举报