日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 编程资源 > 编程问答 >内容正文

编程问答

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

發(fā)布時(shí)間:2024/7/5 编程问答 33 豆豆
生活随笔 收集整理的這篇文章主要介紹了 LeetCode 1973. Count Nodes Equal to Sum of Descendants(DFS) 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

文章目錄

    • 1. 題目
    • 2. 解題

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:

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, 10^5]. 0 <= Node.val <= 10^5

來(lái)源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/count-nodes-equal-to-sum-of-descendants
著作權(quán)歸領(lǐng)扣網(wǎng)絡(luò)所有。商業(yè)轉(zhuǎn)載請(qǐng)聯(lián)系官方授權(quán),非商業(yè)轉(zhuǎn)載請(qǐng)注明出處。

2. 解題

  • 自底向上,后序遍歷
/*** 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/

長(zhǎng)按或掃碼關(guān)注我的公眾號(hào)(Michael阿明),一起加油、一起學(xué)習(xí)進(jìn)步!

總結(jié)

以上是生活随笔為你收集整理的LeetCode 1973. Count Nodes Equal to Sum of Descendants(DFS)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。