前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >LeetCode 1973. Count Nodes Equal to Sum of Descendants(DFS)

LeetCode 1973. Count Nodes Equal to Sum of Descendants(DFS)

作者头像
Michael阿明
发布2021-09-06 11:41:12
4300
发布2021-09-06 11:41:12
举报
文章被收录于专栏:Michael阿明学习之路

文章目录

1. 题目

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:

在这里插入图片描述
在这里插入图片描述
代码语言:javascript
复制
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:

在这里插入图片描述
在这里插入图片描述
代码语言:javascript
复制
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:

在这里插入图片描述
在这里插入图片描述
代码语言:javascript
复制
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, 10^5].
0 <= Node.val <= 10^5

来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/count-nodes-equal-to-sum-of-descendants 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

2. 解题

  • 自底向上,后序遍历
代码语言:javascript
复制
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
    int ans = 0;
public:
    int equalToDescendants(TreeNode* root) {
        dfs(root);
        return ans;
    }
    long long dfs(TreeNode* root)
    {
        if(!root) return 0;
        auto l = dfs(root->left);
        auto r = dfs(root->right);
        if(root->val == l+r)
            ans++;
        return l+r+root->val;
    }
};

360 ms 195.4 MB C++


我的CSDN博客地址 https://michael.blog.csdn.net/

长按或扫码关注我的公众号(Michael阿明),一起加油、一起学习进步!

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2021/08/21 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 文章目录
  • 1. 题目
  • 2. 解题
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档